Monday 5 August 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...