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!