如果文件不存在,fs.watch是否有错误处理程序

fs.watch is there an error handler if file does not exist?

本文关键字:是否 有错误 处理 程序 watch fs 文件 不存在 如果      更新时间:2023-09-26

nodejs fs模块中。

const fs = require('fs');
fs.watch('target.txt', function() {
console.log("File 'target.txt' just changed!");
});

如果文件不存在,我得到:

fs.js:1172
    throw errnoException(err, 'watch');
          ^
Error: watch ENOENT
    at exports._errnoException (util.js:746:11)
    at FSWatcher.start (fs.js:1172:11)

如果文件不存在,是否有err回调?在这里处理错误的正确方法是什么?

您可以尝试这样包装它,它会在做任何事情之前检查是否存在文件。

    if (fs.existsSync('target.txt')) {
        fs.watch('target.txt', function() {
           console.log("File 'target.txt' just changed!");
        });
    }
相关文章: