In the fs module of Node.js, questions about fs.watch

  node.js, question

When learning the fs module of Node.js, one function is fs.watch, which is used to monitor whether the file directory has changed. Then the following test code is written:

var fs = require('fs');
 var watch = './watch';
 var done = './done';
 
 fs.watch(watch, (err, file) => {
 if (file) {
 console.log(file);
 Fs.rename(watch plus'/'plus file, done plus'/'plus file, (err) => {)
 if (err) console.error(err);
 });
 bracket
 });

There is something wrong with this program. Assuming I touch 1.txt in the watch directory, I will actually throw an exception:

lgtdeMacBook-Pro:test lgt$ node test.js
 1.txt
 1.txt
 { [Error: ENOENT: no such file or directory, rename './watch/1.txt' -> './done/1.txt']
 errno: -2,
 code: 'ENOENT',
 syscall: 'rename',
 path: './watch/1.txt',
 dest: './done/1.txt' }

It is obvious here that 1.txt actually appeared twice. The first time we successfully transferred from the watch directory to the done directory through rename, resulting in the second rename when the 1.txt file no longer exists.

Questions:

  1. Why does 1.txt appear twice?

Because you triggered it again when rename

LookDocuments for fs.watchThe callback signature is not (err, file) but (event, file). The first parameter tells you what happened