snippetjavascriptMinor
Read multiple files async
Viewed 0 times
asyncfilesmultipleread
Problem
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?
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 < data.length; j++){
console.log(data[j].toString());
}
});
});
}Solution
I believe you can shorten it to just
Right now, you're first calling
But
The
So you don't need the buffer, which means you don't need
function testAsync() {
var files = ['Statistics_Schema.json', 'seriesData'];
async.map(files, fs.readFile, function (err, data) {
for(var i = 0, l = data.length ; i < 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.Code Snippets
function testAsync() {
var files = ['Statistics_Schema.json', 'seriesData'];
async.map(files, fs.readFile, function (err, data) {
for(var i = 0, l = data.length ; i < l ; i++) {
console.log( data[i].toString() );
}
});
}Context
StackExchange Code Review Q#59767, answer score: 2
Revisions (0)
No revisions yet.