Monday, August 5, 2019

node.js - Pass additional parameter to Javascript callback function





I need to watch a small number of directories in a Node.JS application:



function updated(event, filename){
log("CHANGED\t/share/channels/" + filename);
}
for(i in channels)
fs.watch('share/channels/' + channels[i], {persistent: false}, updated);


The problem is that fs.watch only passes the filename to the callback function, without including the directory it's in. Is there a way I can somehow pass in an extra parameter to the updated() function so it knows where the file is?




I think I'm looking for something similar to Python's functools.partial, if that helps any.


Answer



You can use Function.bind:



function updated(extraInformation, event, filename) {
log("CHANGED\t/share/channels/" + extraInformation + filename);
}

for(i in channels)

fs.watch('share/channels/' + channels[i], {persistent: false},
updated.bind(null, 'wherever/it/is/'));

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...