Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs. watcher returned from fs.watch() listen 'error' event does not trigger

Tags:

node.js

I add 'error' event Listener to watcher returned from fs.watch().

But error event handler does not trigger when I watch a file which is not existed.

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 give me this output:

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)

There is no filename is not correct log. which case will trigger watcher error event handler?

like image 757
slideshowp2 Avatar asked Mar 08 '18 12:03

slideshowp2


1 Answers

The fs.FSWatcher docs says that it is returned on a successful fs.watch() call. Check the returned object, maybe it is an Error (ENOENT) and not an FSWatcher you expect.

(Actually I believe an ENOENT is thrown, so your watcher.on(...) calls are never executed. You can use a try-catch to make sure.)

like image 141
István Rábel Avatar answered Nov 15 '22 03:11

István Rábel