Read multiple files async I want to read multiple files simultaneously and apply the same function on data.

This code works correctly, but can someone please suggest any better way of writing this?

function fileread(path,stats,callback){
   var buffer = new Buffer(stats.size);
   fs.readFile(path, buffer, function(err, data){
      if(err){
         throw err;
      }

      callback(null, data);
   });
}

function testAsync() {
    var files = ['Statistics_Schema.json','seriesData'];
    async.map(files, fs.stat, function(err, stats){
       var i=0;
       async.map(files, function(path, callback){
          fileread(path, stats[i++], callback);
          },function(err, data){
                for(var j=0; j &lt; data.length; j++){
                 console.log(data[j].toString());
                }
           });
    });
}
I believe you can shorten it to just

function testAsync() {
    var files = ['Statistics_Schema.json', 'seriesData'];
    async.map(files, fs.readFile, function (err, data) {
        for(var i = 0, l = data.length ; i &lt; l ; i++) {
            console.log( data[i].toString() );
        }
    });
}


Right now, you're first calling fs.stat on each file, only so you can create a buffer in your fileread method.

But fs.readFile does not take a buffer argument. It takes an options object (and there's no buffer option).

The Buffer object you're passing is an object, though, so Node doesn't complain. It just doesn't find any relevant fileRead options in that object either, so it's basically ignored.

So you don't need the buffer, which means you don't need fs.stat, which means you can skip almost all of your code.