node.js - Node 。从 fs.watch() 返回的观察者监听 'error' 事件未触发

标签 node.js

我将“错误”事件监听器添加到从 fs.watch() 返回的 watcher 中。

但是当我查看不存在的文件时,error 事件处理程序不会触发。

const filename = 'test/target.txt';
const filenameNotExist = 'test/not-exist-target.txt';

console.log('Now watching the target.txt for changes...');

const watcher = fs.watch(filenameNotExist || filename);

watcher.on('change', (eventType, fname) => {
  switch (eventType) {
    case 'rename':
      console.log(`file ${fname} renamed`);
      break;
    case 'change':
      console.log(`file ${fname} changed`);
      break;
    default:
      break;
  }
});

// error event handler does not trigger.
watcher.on('error', err => {
  console.log('filename is not correct'); 
  if (err) throw err;
});

stdout 给我这个输出:

Now watching the target.txt for changes...
fs.js:1384
    throw error;
    ^

Error: watch test/not-exist-target.txt ENOENT
    at _errnoException (util.js:1041:11)
    at FSWatcher.start (fs.js:1382:19)
    at Object.fs.watch (fs.js:1408:11)
    at Object.<anonymous> (/Users/elsa/workspace/Training.nodejs/examples/api/fs/watcher.js:10:20)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Function.Module.runMain (module.js:609:10)

没有文件名不正确日志。 哪种情况会触发观察者 error 事件处理程序?

最佳答案

fs.FSWatcher文档说它在成功 fs.watch() 调用时返回。检查返回的对象,也许它是一个错误(ENOENT),而不是您期望的 FSWatcher。

(实际上,我相信 ENOENT 被抛出,因此您的 watcher.on(...) 调用永远不会执行。您可以使用 try-catch 来使当然。)

关于node.js - Node 。从 fs.watch() 返回的观察者监听 'error' 事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49172605/

相关文章:

node.js - Express 中的模块化路线

node.js - 类验证器不区分大小写的枚举验证?

node.js - 尝试代理到 : localhost:5000 时发生 Docker 错误

javascript - 在 NodeJS 中使用 process.argv 时行为不一致

node.js - NodeJS、MSSQL 批量从 API 获取并保存天气观测结果

angularjs - 如何将 session 变量从express/node传递到Angular?

node.js - req.query 在 nodejs 的 Http.createserver 中不起作用?

javascript - 如何将 jsdom.jQueryify 与 Jasmine Node 一起使用?

json - 语法错误: Unexpected token } curly brace in JSON

node.js - 如何更新 Mongo 集合中的部分?