我将"错误"事件侦听器添加到从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;
});
标准输出给我这个输出:
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
日志。哪种情况将触发事件处理程序error
观察程序?
fs.FSWatcher 文档说它在成功的fs.watch()
调用时返回。检查返回的对象,也许它是一个错误(ENOENT(,而不是您期望的 FSWatcher。
(实际上,我相信会抛出一个 ENOENT,所以你的watcher.on(...)
调用永远不会被执行。您可以使用 try-catch 来确保。