Display directiry nodejs code example

Example 1: 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 2: nodejs readdir

const fs = require("fs")
fs.readdir("./myfolder", (err, data) => {
	if(err) throw err
  	console.log(data)
})

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))