Promises with fs and bluebird
The code can be made shorter by using generic promisification and the .map
method:
var Promise = require("bluebird");var fs = Promise.promisifyAll(require("fs")); //This is most convenient way if it works for youvar directory = "templates";var getFiles = function () { return fs.readdirAsync(directory);};var getContent = function (filename) { return fs.readFileAsync(directory + "/" + filename, "utf8");};getFiles().map(function (filename) { return getContent(filename);}).then(function (content) { console.log("so this is what we got: ", content)});
In fact you could trim this even further since the functions are not pulling their weight anymore:
var Promise = require("bluebird");var fs = Promise.promisifyAll(require("fs")); //This is most convenient way if it works for youvar directory = "templates";fs.readdirAsync(directory).map(function (filename) { return fs.readFileAsync(directory + "/" + filename, "utf8");}).then(function (content) { console.log("so this is what we got: ", content)});
.map
should be your bread and butter method when working with collections - it is really powerful as it works for anything from a promise for an array of promises that maps to further promises to any mix of direct values in-between.