I accidentally typed await(await stat(content... and it worked. Not sure if this is valid syntax, or there is a better way to do it? I'm trying to read all the files that are directories and do not match my regex.
const fs = require('fs')
const path = require('path')
const content = path.resolve('.') + '/docs' + '/'
const util = require('util');
const stat = util.promisify(fs.stat)
const readDir = util.promisify(fs.readdir)
const directories = 'docs/';
const exclude = new RegExp(/^(adir|\.somedir)/,'i');
let newFiles = {}
async function main(){
const ls = await readDir(directories)
console.log('starting....');
let newArray = []
for (let index = 0; index < ls.length; index++) {
let x = await (await stat(content + ls[index])).isDirectory()
let file = ls[index]
if (x && !(exclude.test(file))){newArray.push(file)}
console.log('x is ',x);
}
console.log('new filtered array: ', newArray);
}
ls
My advice would be not to put all of your eggs in one basket. We can write an ultra fast
lsfunction using Node's fs.Dirent objects and bypass the need for a slowfs.statcall on each file -To test it out, let's add some popular
npmpackages so we have a large hierarchy to test our our program. We'll install the lot and count the number of directories and files -Now let's run our program and
timeit -dirs
If we only want directories, we can write
dirsas a simple specialization of our genericls-Now compare it against our program
exclude
If we want to
excludecertain directories or files, we can write it generically as well -reorganize
In our file system extensions module,
fsext, we wrote two functions that work on any iterables, not just thelsordirs. I would suggest breaking these out into their ownitermodule. This type of reorganization helps decouple concerns and maximize code reuse throughout your entire program -search
Looking for a specific file or folder? Read on in this Q&A to implement
search.