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

标签 javascript node.js

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!");
        });
    }

关于javascript - fs.watch 如果文件不存在,是否有错误处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36989315/

相关文章:

javascript - 类型错误 : Cannot read property 'reduce' of undefined when using ftp-deploy

javascript - Node 是有状态的吗? Node能否在内存中维护变量

当它是一个对象时,具有转义字符问题的 Javascript 会变成两次

javascript - AngularJS 文件上传发送陈旧的 formData

javascript - Safari 扩展中的上下文菜单

javascript - 从 jQuery 设置 cookie 并从 php 读取的正确方法

node.js - Node.js 中的负载均衡

javascript - 似乎无法使 window.focus 和 window.onblur 适应我的情况

javascript - Google 网站优化工具和用户定义的变量

node.js - 类型错误 : Cannot read property 'list' of undefined of balanceTransactions