PASSWORD RESET

Your destination for complete Tech news

how to display all files in a directory in Node JS?

1.2K 0
< 1 min read

You can use the built-in fs (file system) module in Node.js to display all files in a directory. Here’s an example of how to achieve this:

const fs = require('fs');
const path = require('path');

const directoryPath = '/path/to/your/directory';

fs.readdir(directoryPath, (err, files) => {
  if (err) {
    console.error('Error reading directory:', err);
    return;
  }

  files.forEach(file => {
    const filePath = path.join(directoryPath, file);
    console.log(filePath);
  });
});

Replace 'path/to/your/directory' with the actual path of the directory you want to list files from. The readdir function reads the contents of the specified directory and passes an array of file names to the callback function. For each file, the example code constructs the full file path using path.join() and then prints it to the console.

Keep in mind that the code above only lists the immediate files in the directory, not files within subdirectories. If you want to list files recursively, you will need to implement a recursive function that traverses subdirectories as well.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.