Home  >  Article  >  Web Front-end  >  How Can I List All Files in a Directory Using Node.js?

How Can I List All Files in a Directory Using Node.js?

Barbara Streisand
Barbara StreisandOriginal
2024-11-24 01:43:14977browse

How Can I List All Files in a Directory Using Node.js?

Finding All Filenames in a Directory in Node.js

In Node.js, obtaining a list of filenames present in a directory involves utilizing the fs module. The two primary methods for this task are fs.readdir and fs.readdirSync.

fs.readdir

This asynchronous method accepts a directory path and a callback function. When the read process is complete, the callback is invoked with an array containing the filenames found in the directory. Here's an example:

const testFolder = './tests/';
const fs = require('fs');

fs.readdir(testFolder, (err, files) => {
  if (err) throw err;

  files.forEach(file => {
    console.log(file);
  });
});

fs.readdirSync

Asynchronous, this method operates synchronously. It returns an array of filenames immediately upon completion of the read process. This blocks further execution until the operation finishes. For instance:

const testFolder = './tests/';
const fs = require('fs');

fs.readdirSync(testFolder).forEach(file => {
  console.log(file);
});

Difference Between the Methods

fs.readdir is asynchronous, requiring a callback for execution upon the completion of the read process. This allows other code to run concurrently.

Conversely, fs.readdirSync is synchronous, meaning it executes immediately and halts code execution until the read process is complete.

The above is the detailed content of How Can I List All Files in a Directory Using Node.js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn