简体   繁体   中英

Node.js file system: Promise once read all files

I am using Node.js file system to build an array of file paths. I would like to know when all files have been read, so I could work further with my array.

Sequence of events:

  1. Go into a folder
  2. Get a path of each file
  3. Put each path into an array
  4. Let me know once you're done

Code:

'use strict';

const fs = require('fs');

function readDirectory(path) {
  return new Promise((resolve, reject) => {
    const files = [];
    fs.readdir(path, (err, contents) => {
      if (err) {
        reject(err);
      }
      contents.forEach((file) => {
        const pathname = `${ path }/${ file }`;
        getFilesFromPath(pathname).then(() => {
          console.log('pathname', pathname);
          files.push(pathname);
        });
        resolve(files);
      });
    });
  });
}

function getFilesFromPath(path) {
  return new Promise((resolve, reject) => {
    const stat = fs.statSync(path);

    if (stat.isFile()) {
      fs.readFile(path, 'utf8', (err, data) => {
        if (err) {
          reject(err);
        } else {
          resolve(data);
        }
      });
    } else if (stat.isDirectory()) {
      readDirectory(path);
    }
  });
}

getFilesFromPath('./dist');

Would be great to glue with:

Promise.all(files).then(() => {
    // do stuff
})

Your suggestion pretty much works - did you try it? Here's a typical way of doing it:

getFilesFromPath( path ).then( files => {
   const filePromises = files.map( readFile );
   return Promises.all( filePromises );
}).then( fileContentsArray => {
   //do stuff - the array will contain the contents of each file
});

You'll have to write the "readFile()" function yourself, but looks like you got that covered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM