Created
February 20, 2012 12:03
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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