Created
August 8, 2015 22:03
-
-
Save ischenkodv/194e65f775c372fc012f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var fs = require('fs'); | |
var files = ['foo.txt', 'bar.txt', 'baz.txt']; | |
var promises = []; | |
for (var i = 0; i < files.length; i++) { | |
promises.push(readFile(files[i])); | |
} | |
Promise.all(promises).then(function(results) { | |
// results - array with 3 text elements. | |
console.log('results', results); | |
}).catch(function(error) { | |
console.log('error', error); | |
}); | |
function readFile(name) { | |
return new Promise(function(resolve, reject) { | |
var result = ''; | |
var stream = fs.createReadStream(name, {encoding: 'utf8'}).on( | |
'readable', | |
function(s) { | |
var buf; | |
while ((buf = stream.read()) !== null) { | |
result += buf; | |
} | |
} | |
).once('end', function() { | |
resolve(result); | |
}).once('error', function(error) { | |
reject(error); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Очень изящно. Благодарствую!