Node.js - List files in a directory

Posted on 20th January 2017

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.

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.