In the fs module of Node.js, questions about

  node.js, question

When learning the fs module of Node.js, one function is, 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';, (err, file) => {
 if (file) {
 Fs.rename(watch plus'/'plus file, done plus'/'plus file, (err) => {)
 if (err) console.error(err);

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
 { [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.


  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