Get List of all files in a directory in Node.js

Get List of all files in a directory in Node.js

Image for postnode.js fs

Do you need to get all files present in the directory or you want to scan a directory for files using node.js, then you?re on the correct web page because in this Nodejs How to Tutorial, we will learning How to get the list of all files in a directory in Node.js.

We will be using Node.js fs core module to get all files in the directory, we can use following fsmethods.

  • fs.readdir(path, callbackFunction) ? This method will read all files in the directory.You need to pass directory path as the first argument and in the second argument, you can any callback function.
  • path.join() ? This method of node.js path module, we will be using to get the path of the directory and This will join all given path segments together.

Steps to get list of all the files in a directory in Node.js

  1. Load all the required Nodejs Packages using ?require?.
  2. Get the path of the directory using path.join() method.
  3. Pass the directory path and callback function in fs.readdir(path, callbackFunction) Method.
  4. The callback function should have error handling and result handling logic.
  5. inside callback function handle the error and run forEach on the array of files list from the directory.
  6. Apply your logic for each file or all the files inside the forEach function.

Full code:

first appeared on Web Development Blog StackFrame.

19