node js get files in directory code example

Example 1: 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 2: 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 3: how to get file name in directory node js

const path = require('path')

//...

//inside the `for` loop
const stat = fs.lstatSync(path.join(dir, file))