Skip to content

Instantly share code, notes, and snippets.

@senthilmpro
Last active February 14, 2019 00:20
Show Gist options
  • Save senthilmpro/d621187475ceb3bcffa9020f3cd825e2 to your computer and use it in GitHub Desktop.
Save senthilmpro/d621187475ceb3bcffa9020f3cd825e2 to your computer and use it in GitHub Desktop.
node.js read files from a directory
//requiring path and fs modules
const path = require('path');
const fs = require('fs');
/**
* Read contents of files inside a folder.
* @param {*} folderName
* @param {*} rootDir
*
* @example : readFolder("data", __dirname)
*/
function readFolder(folderName, rootDir) {
const dirPath = path.join(rootDir, folderName);
//passsing directoryPath and callback function
fs.readdir(dirPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//list files
files.forEach(function (file) {
console.log(file);
});
});
}
module.exports = {
readFolder: readFolder
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment