Node.js - List files in a directory

The Node.js native module fs (file system) provides wrappers for file input/output. The following code accepts an optional path argument and lists all the files in that path. In the absence of any argument, it lists the files in the current directory.

fileList.js


//Accepts an optional path argument and lists all files in the path.

var fs = require('fs');
var dir;

//If argument is missing, use current directory
if (process.argv.length <= 2) {
    dir = __dirname;
}
else {
    dir = process.argv[2];
}

fs.readdir(dir, function(err, files) {
   if (err) {
	   console.log("Error reading " + dir);
	   process.exit(1);
   }
   console.log("Listing files in Directory " + dir);
   files.forEach(function(f) {
      console.log(f);
    });
});

The code checks if an argument was provided and sets the variable dir to that path. If no argument was provided, it uses the __dirname global variable. The __dirname holds the path to the script that is currently running.

The path is passed to the fs.readdir() method along with a callback function. The callback takes arguments (err,files) where err is the error and files is the array with all the file names in the directory. Inside the callback function, each filename is logged into the console.


Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.