node get all files in folder

To get all the files in a folder using Node.js, you can follow these steps:

  1. Import the 'fs' module: Start by importing the 'fs' module, which stands for 'file system'. This module provides methods for interacting with the file system in Node.js. You can import the module using the require keyword like this:
const fs = require('fs');
  1. Use the 'readdir' method: The 'readdir' method is used to read the contents of a directory. It takes two arguments: the path of the directory and a callback function. The callback function will be called with an error object and an array of files in the directory. You can use the readdir method like this:
fs.readdir('/path/to/directory', (err, files) => {
  if (err) {
    // Handle error
  } else {
    // Process files
  }
});
  1. Iterate over the files: In the callback function of the 'readdir' method, you can iterate over the files array to process each file. You can use a 'for' loop or any other looping mechanism to iterate over the files. Here's an example using a 'for' loop:
fs.readdir('/path/to/directory', (err, files) => {
  if (err) {
    // Handle error
  } else {
    for (let i = 0; i < files.length; i++) {
      // Process each file
      console.log(files[i]);
    }
  }
});
  1. Handle errors: In case there is an error while reading the directory, the 'readdir' method will pass an error object to the callback function. You can handle the error by checking if the 'err' argument is truthy and take appropriate action.

That's it! By following these steps, you can get all the files in a folder using Node.js. Remember to replace '/path/to/directory' with the actual path to the directory you want to read.