Multiple path.exists callbacks, how to know which file the return status is for?
The node.js built in library function for checking if a file exists asynchronously only supplies a boolean "exists" to the callback. I need to check if multiple files exists which seems problematic. How do I know for which file the response is?
Is the execution order of the callbacks guaranteed or something? Or can I supply the index to the callback somehow that I haven't thought of? Obviously my attempt here with "var k" failed. :/
var path = require('path');
var sys = require('sys');
var paths = new Array();
paths.push('file_0');
paths.push('file_1');
paths.push('file_2');
for (var i = 0; i < paths.length; i++)
{
var k = i;
path.exists(paths[i], function(exists) {
var j = i;
sys.puts("One of the files has this status: " + exists + " but which one?");
sys.puts("j is: "+j);
sys.puts("k is: "+k);
});
}
The output from a run is:
$ node test.js
One of the files has this status: false but which one?
j is: 3
k开发者_Go百科 is: 2
One of the files has this status: false but which one?
j is: 3
k is: 2
One of the files has this status: false but which one?
j is: 3
k is: 2
Unfortunately, Javascript hoists all variable declarations to the top of the function, which is stupid and unintuitive. Some workarounds: JavaScript variable binding and loop
精彩评论