javascript - Reading files in multiple directories, matching filenames with their data using Node and Promises -


i have array of directories.

var directories = ['/dir1', '/dir2']; 

i want read files under these directories, , in end have object matches filenames base64/utf8 data. in case these files images. resulting object might like:

var result = {  '/dir1': {   'file1': 'ivborw0kggoaaaansuheugaaaoeaaadhcaiaaacx0uutaaaagxrfwhrtb2z0d2fyzqbbzg9izsbjbwf...',   'file2': 'ivborw0kggoaaaansuheugaaaoeaaadhcaiaaacx0uutaaaagxrfwhrtb2z0d2fyzqbbzg9izsbjbwf...'     } } 

i implemented callback hell, when try promises, i'm not sure how pass directory information, , filename succeeding then() , map() functions.

in 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) {     // directory's files these?     return files;   }) 

the next step iterating on files , reading data.

i don't mind if answer es6, bluebird, or q.

the easiest way bluebird use props:

function getfiles(paths) { // array of file/directory paths     return promise.props(paths.reduce(function (obj, path) {         obj[path.split("/").pop()] = fs.statasync(path).then(function (stat) {             if (stat.isdirectory())                 return fs.readdirasync(path).map(function (p) {                     return path + "/" + p;                 }).then(getfiles);             else if (stat.isfile())                 return fs.readfileasync(path);         }).error(function (e) {             console.error("unable read " + path + ", because: ", e.message);             // return undefined; implied         });         return obj;     }, {})); } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -