HomeToolsAbout

Node Filesystem

fs.readdirSync()

Grab only the files or the directories inside of the specified path

const fs = require('fs'); // include file type const dirOrFiles = fs.readdirSync('directory_path', { withFileTypes: true }); // filter for files const filesNames = dirOrFiles .filter(dirent => dirent.isFile()) .map(dirent => dirent.name); // filter for directories const directoryNames = dirOrFiles .filter(dirent => dirent.isDirectory()) .map(dirent => dirent.name);

fs.readFile

// encoding as utf8 // returns file content as string fs.readFile("dir/file", 'utf8', function(err, data ) { console.log( data ); });

fs.readFileSync

Synchronous version for readFile. Does not take a callback function.

const fs = require('fs'); const fileName = "myFile.txt"; const fileData = fs.readFileSync(fileName, "utf8");

__dirname

__dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file

  • value of directory where the current running JS file resides

vs process.cwd()

process.cwd() returns the value of directory where we run the Node process

AboutContact