Skip to content

Instantly share code, notes, and snippets.

@dre1080
Created February 20, 2012 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dre1080/1868936 to your computer and use it in GitHub Desktop.
Save dre1080/1868936 to your computer and use it in GitHub Desktop.
Everything in node happens at the same time, which means, unless you're doing your processing inside your callbacks, you cannot guarantee asynchronous functions have completed yet.
/**
* Source: http://stackoverflow.com/questions/6287908/nodejs-express-fs-iterating-files-into-array-or-object-failing
*/
var fs = require('fs'),
EventEmitter = require('events').EventEmitter,
filesEmitter = new EventEmitter(),
files = [];
// this event will be called when all files have been added to the files array
filesEmitter.on('files ready',function() {
console.log(files);
});
// read all files from current directory
fs.readdir('.',function(err,files){
if(err) throw err;
files.forEach(function(file){
files.push(file);
});
filesEmitter.emit('files ready'); // trigger files_ready event
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment