HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How do you get a list of the names of all files present in a directory in Node.js?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
directoryyouhowfilesthelistpresentnodeallget

Problem

I'm trying to get a list of the names of all the files present in a directory using Node.js. I want output that is an array of filenames. How can I do this?

Solution

You can use the fs.readdir or fs.readdirSync methods. fs is included in Node.js core, so there's no need to install anything.

fs.readdir

const testFolder = './tests/';
const fs = require('fs');

fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    // will also include directory names
    console.log(file);
  });
});


fs.readdirSync

const testFolder = './tests/';
const fs = require('fs');

fs.readdirSync(testFolder).forEach(file => {
  // will also include directory names
  console.log(file);
});


The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.

The second is synchronous, it will return the file name array, but it will stop any further execution of your code until the read process ends.

Code Snippets

const testFolder = './tests/';
const fs = require('fs');

fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    // will also include directory names
    console.log(file);
  });
});
const testFolder = './tests/';
const fs = require('fs');

fs.readdirSync(testFolder).forEach(file => {
  // will also include directory names
  console.log(file);
});

Context

Stack Overflow Q#2727167, score: 2218

Revisions (0)

No revisions yet.