node read 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 list files in directory
const path = require('path');
const fs = require('fs');
const directoryPath = path.join(__dirname, 'Documents');
fs.readdir(directoryPath, function (err, files) {
if (err) {
return console.log('Unable to scan directory: ' + err);
}
files.forEach(function (file) {
console.log(file);
});
});
Example 3: 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 4: nodejs readdir
const fs = require("fs")
fs.readdir("./myfolder", (err, data) => {
if(err) throw err
console.log(data)
})
Example 5: how to get file name in directory node js
const path = require('path')
const stat = fs.lstatSync(path.join(dir, file))
Example 6: read directory in node js
const testFolder = './tests/';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
console.log(file);
});
});