Skip to content Skip to sidebar Skip to footer

Chaining `fs.readdir` With A `.then` To Return An Array

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

Solution 1:

fs.readdir is callback based, so you can either promisify it using bluebird or Node.js util package (or writing a simple implementation of it yourself), or simply wrap the call in a promise, like so:

// Wrapped in a promisenewPromise((resolve, reject) => {
    return fs.readdir('/folderpath', (err, filenames) => err != null ? reject(err) : resolve(filenames))
})

Or the custom promisify function:

// Custom promisifyfunctionpromisify(fn) {
  /**
   * @param {...Any} params The params to pass into *fn*
   * @return {Promise<Any|Any[]>}
   */returnfunctionpromisified(...params) {
    returnnew Promise((resolve, reject) => fn(...params.concat([(err, ...args) => err ? reject(err) : resolve( args.length < 2 ? args[0] : args )])))
  }
}

constreaddirAsync = promisify(fs.readdir)
readdirAsync('./folderpath').then(filenames => console.log(filenames))

Solution 2:

Just plain javascript, no libs:

functionfoo (folder, enconding) {
    returnnewPromise(function(resolve, reject) {
        fs.readdir(folder,enconding, function(err, filenames){
            if (err) 
                reject(err); 
            elseresolve(filenames);
        });
    });
};

e.g

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

Solution 3:

I figured it out; I just needed to use statSync instead of stat

const fs = require('fs');

var arr = [];

var files = fs.readdirSync(folder);

files.forEach(file => {
  let fileStat = fs.statSync(folder + '/' + file).isDirectory();
  if(!fileStat) {
    arr.push(file);
  }
});

console.log(arr);

Solution 4:

You can now use ES6 destructuring assignment (documentation) :

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

console.log(FILES);

Solution 5:

if you want to use a promise instead of a callback you can promisify fs.

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

fs.readdirAsync('./some').then()

http://bluebirdjs.com/docs/api/promise.promisifyall.html

Post a Comment for "Chaining `fs.readdir` With A `.then` To Return An Array"