move new files from one location to another using chokidar to monitor in nodejs and powershell script

434 Views Asked by At

I am new to node.js and am trying to setup a script to monitor a folder and move any files saved there to another location, script works for 1 file but shows errors when moving multiple files even though it does actually move them - reports 2nd & 3rd file as missing. I am guessing this is due to async/sync method of node and I probably need to use callback or promise but need help to understand how to use in this example.

Errors:

(node:1812) UnhandledPromiseRejectionWarning: TypeError: callback is not a function

(node:1812) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:1812) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

EOI_HUzDtR-mwMove-Item : Cannot find path 'C:\test2\test.txt' because it does not exist.

Code:

const filelocation = ('c:/test/');
const destlocation = ('c:/new_folder/');
const watcher = chokidar.watch(".", { ignored: /^\./, persistent: true, cwd: filelocation, awaitWriteFinish: true });

watcher.on('add', (path) => {
    var FileName = path;
    logger.info(`File ${FileName} has been added to ${filelocation}`);
    Movefile({param1: FileName, param2: filelocation, param3: destlocation});
});

function Movefile(options) {
    var FileName = options.param1;
    var filelocation = options.param2;
    var destlocation = options.param3;
    logger.info(`Started move for file ${FileName} in location ${filelocation} to location ${destlocation}`);
    ps.addCommand("./move_file.ps1");
    ps.addParameters([{ name: 'file', value: FileName }, { name: 'flocation', value: filelocation }, { name: 'dlocation', value: destlocation }]);
    ps.invoke()
        .then(output => {
            logger.info(`Completed move of file ${FileName}`);
            //ps.dispose();
        })
        .catch(err => {
            logger.error('Move file failed to execute', err);
            //ps.dispose();
        });
}
0

There are 0 best solutions below