Man
Man

Reputation: 772

confuse in fs.watch() callback function in node.js

fs.watch('./tmp', {encoding: 'buffer'}, (eventType, filename) => {
  if (filename)
    console.log(filename);
    // Prints: <Buffer ...>
});

it is copy from node.js file system 's Class: fs.FSWatcher documentation

documentation describe eventType is string type and it can be 'change' or 'rename' so i write code like bellow

fs.watch('./public/dir',function('change','xx.txt'){
    console.log('file changed');
});

but it SyntaxError: Unexpected string

i don't understand what is eventType and filename

plz describe what is it.

Upvotes: 0

Views: 1240

Answers (1)

Mykola Borysyuk
Mykola Borysyuk

Reputation: 3411

The listener callback gets two arguments (eventType, filename). eventType is either 'rename' or 'change'.

Filename is the name of the file which triggered the event. from docs. https://nodejs.org/api/fs.html#fs_fs_watch_filename_options_listener

eventType, filename <- it just callback variables from listener.

To fix you need to do like this.

fs.watch('./public/dir',function(typeOfEvent, nameOfFile){
    console.log(typeOfEvent);
    console.log(nameOfFile);
});

Hope this helps.

Upvotes: 1

Related Questions