How do I check whether it is a file or a directory with the NodeJS FS Promises API?

I want to get all files recursively from a directory. Therefore I'm using Node JS fs standard library. I made a function that is doing exactly what I want and which looks like the following.

const fs = require('fs');

function crawl(dir, files) {
  var files = files || [];
  fs.readdirSync(dir).forEach((file) => {
    if (fs.lstatSync(dir + '/' + file).isDirectory()) {
      files = crawl(dir + '/' + file + '/', files);
    } else {
  return files

console.log(crawl(__dirname + '/myDirectory'));

Now my problem is that I read a lot about that the way I solved the problem is synchronous. It seems like that a lot of people are claiming that synchronous programming is bad for the performance of a program and should be avoided. So I've tried to recreate my function with the FS Promise API but couldn't get it to work because functions like "fs.isDirectory" don't work when using the FS Promise API.

My questions now are:

  • Is synchronous programming really bad and should be avoided
  • How does a function with the Promise API have to look like to produce the same result

Read more here:

Content Attribution

This content was originally published by Yuki at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: