It's just a little question about asynchronous function in nodejs and the good way to create them. the following takes in parameters a repository and an extension name and return the list of the files with the given extension in the given repository
to run
$ node app /path/to/some/reposity someExtension
module.js file
//modules.js
var fs = require('fs');
var path = require('path');
module.exports = function(dir, ext, callback){
//do something
fs.readdir(dir, function(err, data){
if(err){
//EDIT
process.nexTick(function(){
callback(err);
});
//
}
if(data){
var compteur = 0;
var block = [];
for(var i =0 ; i < data.length ; i++){
if(path.extname(data[i]).slice(1) == ext){
block[compteur]= data[i];
compteur++;
}
}
//EDIT
process.nextTick(function(){
callback(null, block);
});
//
}
});
};
app.js file
//app.js
var dir = process.argv[2];
var ext = process.argv[3];
var module = require('./module');
module(dir, ext, function(err, data){
if(err) { throw err;}
var dl = data.length;
for(var i = 0 ; i < dl ; i++){
console.log(data[i]);
}
});
I just wanted to know if it's the good way to do things or if there a better one. Thanks in advance.
I find this nice tutorial on asynchronous function in NodeJS http://howtonode.org/understanding-process-next-tick
returnstatements before thecallback()calls aren't really doing anything useful.function(err, data))<--return callback(..)is a good habit as you might go have a bug where thecallback(..)is called twice !