Home >Web Front-end >JS Tutorial >How to Get a Directory\'s File List Using Node.js?

How to Get a Directory\'s File List Using Node.js?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 08:09:141029browse

How to Get a Directory's File List Using Node.js?

Obtaining a File List in a Directory with Node.js

Retrieving a list of file names from a directory is a common task in Node.js. Node.js core provides the fs module, which simplifies this process. Here's how to do it:

fs.readdir

The fs.readdir method reads the contents of a directory and returns an array of file names asynchronously. The async nature of this method allows Node.js to continue executing without blocking while the read operation is in progress.

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

fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    console.log(file);
  });
});

fs.readdirSync

The fs.readdirSync method behaves similarly to fs.readdir, but it synchronously reads the directory and returns an array of file names. This means that the code execution will pause until the read operation completes.

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

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

The choice between fs.readdir and fs.readdirSync depends on the specific use case. If immediate access to the file list is required, fs.readdirSync can be used. However, if asynchronous execution is preferred, fs.readdir is a more appropriate choice.

The above is the detailed content of How to Get a Directory\'s File List 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