Listing Files

Another common task when working with the file system is listing files and folders in a directory—for example, listing the files in a directory to determine whether they need to be cleaned up, to dynamically operate on the directory structure, etc.

You can access the files in the file system by using one of the following commands to read a list of entries:

fs.readdir(path, callback)fs.readdirSync(path)

If readdirSync() is called, an array of strings representing the entry names in the specified path is returned. In the case of readdir(), the list is passed as the second parameter to the callback function, and an error, if there is one, is passed as the first parameter.

To illustrate the use of readdir(), the code in Listing 6.10 ...

Get Node.js, MongoDB, and AngularJS Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.