I have an array of directories.
var directories = ['/dir1', '/dir2'];
I want to read all files under these directories, and in the end have an object that matches filenames with their base64/utf8 data. In my case these files are images. The resulting object might look like:
var result = {
'/dir1': {
'file1': 'iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAIAAACx0UUtAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWF...',
'file2': 'iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAIAAACx0UUtAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWF...'
}
}
I easily implemented this with a callback hell, but when I try with Promises, I'm not sure how to pass directory information, and filename to succeeding then() and map() functions.
In the example below I'm using Bluebird library:
const Promise = require('bluebird'),
fs = Promise.promisifyAll(require('fs'));
var getFiles = function (dir) {
return fs.readdirAsync(dir);
};
Promise.map(directories, function(directory) {
return getFiles(directory)
}).map(function (files) {
// which directory's files are these?
return files;
})
The next step would be iterating over files and reading their data.
I don't mind if answer is with ES6, Bluebird, or Q.