How to get the names of all files in a folder in Node

Here is how to use Node.js to list the files/folders contained in the file system folder:

const fs = require('fs')

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

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

After obtaining the file reference, you can use it to get its detailed information

const path = require('path')

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

This helps to distinguish between files and folders, for example, usingstat.isDirectory()method.

fswithpathIs a built-in module, no need to use npm to install

Download mine for freeNode.js manual


More node tutorials: