我需要在Node.JS应用程序中观察少量目录:
function updated(event, filename){
log("CHANGED\t/share/channels/" + filename);
}
for(i in channels)
fs.watch('share/channels/' + channels[i], {persistent: false}, updated);
问题是fs.watch只将文件名传递给回调函数,而不包括它所在的目录。有没有办法我可以以某种方式将额外的参数传递给updated()函数,以便它知道文件的位置是
我认为我正在寻找类似于Python functools.partial
的东西,如果这有助于任何事情。
答案 0 :(得分:12)
您可以为每次迭代传递不同的函数:
var getUpdatedFunction = function(folderName) {
return function(event, filename) {
log("CHANGED\t" + folderName + "/" + filename);
};
};
for(i in channels) {
foldername = 'share/channels/' + channels[i];
fs.watch(foldername, {persistent: false}, getUpdatedFunction(foldername));
}
答案 1 :(得分:7)
Doc:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
提示,绑定参数出现在调用时参数之前。
my_hello = 'Hello!'
my_world = {
'antartica': 'cold',
}
anonymous_callback = function (injected1, injected2, param1, param2) {
param1 = param1 ? param1 : 'One';
param2 = param2 ? param2 : 'Two';
console.log('param1: (' + typeof(param1) + ') ' + param1)
console.log('param2: (' + typeof(param2) + ') ' + param2)
console.log('injected1: (' + typeof(injected1) + ') ' + injected1)
console.log('injected2: (' + typeof(injected2) + ') ' + injected2)
console.log(injected2)
}.bind(this, my_hello, my_world)
anonymous_callback('Param 1', 'Param 2')
输出:
param1: (string) Param 1
param2: (string) Param 2
injected1: (string) Hello!
injected2: (object) [object Object]
{ antartica: 'cold' }
答案 2 :(得分:4)
您可以使用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/'));
答案 3 :(得分:0)
您可以就地传递其他回调
function updated(channel, filename) {
log('CHANGED\t ' + channel + '/' + filename);
}
for(i in channels) {
channel = '/share/channels/' + channels[i];
fs.watch(channel, {persistent: false}, function (extra, event, filename) {
updated(channel, filename);
});
}