0

How do you maintain context with asynchronous callbacks, like those used in the filesystem module, in Node.js? I would like to know the filename of the file within the readFile callback, but not sure how to access that:

fs.readdir('directory/', function(err, files) {
  for (var file in files) {
    fs.readFile(files[file], function(err, data) {
      // what file was just read?
    });
  }
});
Rob
  • 7,377
  • 7
  • 36
  • 38
  • Wouldn't `files[file]` be your filename? – Sterling Archer Apr 21 '14 at 21:45
  • 4
    If you use `files.forEach(function(file){` instead of the `for.. in` loop (which you shouldn't be using for an array anyway), that'd create a closure and solve your issue. – Benjamin Gruenbaum Apr 21 '14 at 21:45
  • possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Benjamin Gruenbaum Apr 21 '14 at 21:45
  • @BenjaminGruenbaum thanks! Don't know why I was even using a `for in` there, but more to the point I didn't realize that `.forEach()` was the correct thing to use here. – Rob Apr 21 '14 at 21:53
  • You might consider using Q to "denodify" fs.readdir, and create an array of promises that can then be settled with Q.allSettled, or Q.all – binarygiant Apr 22 '14 at 01:53

0 Answers0