chaining `fs.readdir` with a `.then` to return an array
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 promise
new Promise((resolve, reject) => {
return fs.readdir('/folderpath', (err, filenames) => err != null ? reject(err) : resolve(filenames))
})
Or the custom promisify
function:
// Custom promisify
function promisify(fn) {
/**
* @param {...Any} params The params to pass into *fn*
* @return {Promise<Any|Any[]>}
*/
return function promisified(...params) {
return new Promise((resolve, reject) => fn(...params.concat([(err, ...args) => err ? reject(err) : resolve( args.length < 2 ? args[0] : args )])))
}
}
const readdirAsync = promisify(fs.readdir)
readdirAsync('./folderpath').then(filenames => console.log(filenames))
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);
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));