You can use the f.readdir()
method to list all files available in a directory in Node.js. This method asynchronously reads the contents of the given directory and returns an array of the file names excluding .
and ..
.
Here is an example that reads all files available in a directory and prints their names on the console:
const fs = require('fs')
// directory path
const dir = './node_modules/'
// list all files in the directory
fs.readdir(dir, (err, files) => {
if (err) {
throw err
}
// files object contains all files names
// log them on console
files.forEach(file => {
console.log(file)
})
})
The fs.readdir()
method will throw an error if the given directory doesn't exist.
Alternatively, you can use the readdirSync()
method that works synchronously and returns an array of the names of the files:
const fs = require('fs')
// directory path
const dir = './node_modules/'
// list all files in the directory
try {
const files = fs.readdirSync(dir)
// files object contains all files names
// log them on console
files.forEach(file => {
console.log(file)
})
} catch (err) {
console.log(err)
}
You can also use the promise-based fsPromises.readdir()
method to read the contents of a directory:
const fsPromises = require('fs/promises')
const listFilesAsync = async () => {
try {
// directory path
const dir = './node_modules/'
const files = await fsPromises.readdir(dir)
// files object contains all files names
// log them on console
files.forEach(file => {
console.log(file)
})
} catch (err) {
console.error(err)
}
}
listFilesAsync()
Read this guide to learn more about reading and writing files in a Node.js application.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.