我将“错误”事件监听器添加到从 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/