node fs get all files in directory code example

Example 1: node get all files in folder

fs.readdir('./', (err, files) => {
    files.forEach(file => {
    //   console.log(file);
})});

Example 2: how to get file name in directory node js

const fs = require('fs')

const dir = '/Users/flavio/folder'
const files = fs.readdirSync(dir)

for (const file of files) {
  console.log(file)
}

Example 3: node list files in directory

//requiring path and fs modules
const path = require('path');
const fs = require('fs');
//joining path of directory 
const directoryPath = path.join(__dirname, 'Documents');
//passsing directoryPath and callback function
fs.readdir(directoryPath, function (err, files) {
    //handling error
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    } 
    //listing all files using forEach
    files.forEach(function (file) {
        // Do whatever you want to do with the file
        console.log(file); 
    });
});

Example 4: node js get files in dir

const path = require('path');
const fs = require('fs');

fs.readdir(
  path.resolve(__dirname, 'MyFolder'),
  (err, files) => {
    if (err) throw err;
    
    for (let file of files) {
      console.log(file);
    }
  }
);

Example 5: how to read all files in a folder in node js

fs.readdir('./', (err, files) => {
        files.forEach(file => {
        //   console.log(file);
        }});

Example 6: get all from dir node

const getAllFromDir = source =>
      fs.readdirSync(source).map(name => path.join(source, name));
      console.log(getDirectories("C:/"));