的NodeJS。观察者从fs.watch返回()听'错误'事件不会触发

时间:2018-03-08 12:01:44

标签: node.js

我添加错误'事件来自watcher的{​​{1}}的听众。

但是当我看一个不存在的文件时,fs.watch()事件处理程序不会触发。

error

stdout给我这个输出:

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

没有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) 日志。 哪种情况会触发观察者filename is not correct事件处理程序?

1 个答案:

答案 0 :(得分:0)

fs.FSWatcher文档说它是在成功 fs.watch()来电时返回的。检查返回的对象,可能是错误(ENOENT)而不是您期望的FSWatcher。

(实际上我相信ENOENT是抛出,所以你的watcher.on(...)调用永远不会执行。你可以使用try-catch来确保。)