list folder files in nodejs on linux
Here's an example of how to list the files in a folder in Node.js on Linux:
javascriptconst fs = require("fs");
fs.readdir("/path/to/folder", (err, files) => {
if (err) throw err;
console.log(files);
});
This will return an array of strings representing the filenames in the directory /path/to/folder
.
You can also use the fs.promises.readdir()
method to achieve the same result using promises, like this:
javascriptconst fs = require("fs").promises;
async function listFiles(dir) {
try {
const files = await fs.readdir(dir);
console.log(files);
} catch (err) {
throw err;
}
}
listFiles("/path/to/folder");