chaining `fs.readdir` with a `.then` to return an array

Viewed 20956

I am trying to create an array of specific files in a directory; which will go through a few test cases to make sure it fits a given criteria.

I'm using the fs.readdir method, but it doesn't return a promise meaning I cannot push to an array.

My idea was to populate an array (arr) with the files I actually want to output and then do something with that array. But because readdir is asynchronous and I can't chain a .then() onto it, my plans are quashed.

I've also tried the same thing with readdirSync to no avail.

const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));

var arr = [];

fs.readdirAsync(folder).then( files => {
  files.forEach(file => {
    fs.stat(folder + '/' + file, (err, stats) => {
       if(!stats.isDirectory()) {
         arr.push(file);
        return;
      }
     });
   });
})
.then( () => {
  console.log(arr);
});
8 Answers

Just plain javascript, no libs:

function foo (folder, enconding) {
    return new Promise(function(resolve, reject) {
        fs.readdir(folder,enconding, function(err, filenames){
            if (err) 
                reject(err); 
            else 
                resolve(filenames);
        });
    });
};

e.g

foo(someFolder, "someEncoding")
.then((files) => console.log(files))
.catch((error) => console.log(error));

As of Node.js v10, there is an fs.promises API that supports this:

const fs = require('fs');

var arr = [];

fs.promises.readdir(folder).then( files => {
  files.forEach(file => {
    fs.stat(folder + '/' + file, (err, stats) => {
       if(!stats.isDirectory()) {
         arr.push(file);
        return;
      }
     });
   });
})
.then( () => {
  console.log(arr);
});

You can now use ES6 destructuring assignment (documentation) :

const
    fs = require('fs'),
    FILES = [...fs.readdirSync('src/myfolder')];

console.log(FILES);
new Promise((resolve, reject) => {
    return fs.readdir('/folderpath', (err, filenames) => err ? reject(err) : resolve(filenames))
})

Do not err !== undefined because err is actually null!!

Related