Node.js fs.Dir.read() 方法
fs.Dir.read()方法是文件系统模块中fs.Dir类的内置应用程序编程接口,用于异步读取每个下一个目录(dirent)。
句法:
const fs.Dir.read(callback)
参数:此方法将回调函数作为具有以下参数的参数。
- err:如果发生任何错误。
- dirent:读取后目录的dirent。
返回值:此方法不返回任何值。
下面的程序说明了 Node.js 中fs.Dir.read()方法的使用:
示例 1:
文件名:GFG.js
Javascript
// Node program to demonstrate the
// dir.path() API
const fs = require('fs');
// Initiating async function
async function stop(path) {
// Creating and initiating directory's
// underlying resource handle
const dir = await fs.promises
.opendir(new URL('file:///F:/'));
// Getting all the dirent of the directory
for (var i = 1 ; i<=2 ; i++) {
// Reading each dirent one by one
// by using read() method
dir.read( (err, dirent) => {
// Display each dirent one by one
console.log(`${dirent.name}
${err ? 'does not exist' : 'exists'}`);
});
}
}
// Catching error
stop('./').catch(console.error);
Javascript
// Node program to demonstrate the
// dir.path() API
const fs = require('fs');
// Initiating async function
async function stop(path) {
// Creating and initiating directory's
// underlying resource handle
const dir = await fs.promises.opendir(path);
// Getting all the dirent of the directory
for (var i = 1 ; i<=4 ; i++) {
// Reading each dirent one by one
// by using read() method
dir.read( (err, dirent) => {
// Throwing error
if(err) throw err
// Display each dirent one by one
console.log(dirent.name);
});
}
}
// Catching error
stop('./').catch(console.error);
使用以下命令运行GFG.js文件:
node GFG.js
输出:
示例 2:
文件名:GFG.js
Javascript
// Node program to demonstrate the
// dir.path() API
const fs = require('fs');
// Initiating async function
async function stop(path) {
// Creating and initiating directory's
// underlying resource handle
const dir = await fs.promises.opendir(path);
// Getting all the dirent of the directory
for (var i = 1 ; i<=4 ; i++) {
// Reading each dirent one by one
// by using read() method
dir.read( (err, dirent) => {
// Throwing error
if(err) throw err
// Display each dirent one by one
console.log(dirent.name);
});
}
}
// Catching error
stop('./').catch(console.error);
使用以下命令运行GFG.js文件:
node GFG.js
输出:
注意:上述程序不会在在线 JavaScript 和脚本编辑器上运行。
参考: https://nodejs.org/dist/latest-v12.x/docs/api/fs.html#fs_dir_read_callback