我试图使用Node.js获取目录中所有文件的名称列表。我希望输出文件名数组。我该怎么做?
当前回答
但是,上面的答案不会对目录执行递归搜索。以下是我对递归搜索所做的操作(使用node walk:npm install walk)
var walk = require('walk');
var files = [];
// Walker options
var walker = walk.walk('./test', { followLinks: false });
walker.on('file', function(root, stat, next) {
// Add this file to the list of files
files.push(root + '/' + stat.name);
next();
});
walker.on('end', function() {
console.log(files);
});
其他回答
与ES7一起使用Promise
与mz/fs的异步使用
mz模块提供了核心节点库的预期版本。使用它们很简单。首先安装库。。。
npm install mz
然后
const fs = require('mz/fs');
fs.readdir('./myDir').then(listing => console.log(listing))
.catch(err => console.error(err));
或者,您可以在ES7中的异步函数中编写它们:
async function myReaddir () {
try {
const file = await fs.readdir('./myDir/');
}
catch (err) { console.error( err ) }
};
更新递归列表
一些用户已经指定希望看到递归列表(尽管不在问题中)。。。使用fs promise。它是mz的一个薄包装。
npm install fs-promise;
然后
const fs = require('fs-promise');
fs.walk('./myDir').then(
listing => listing.forEach(file => console.log(file.path))
).catch(err => console.error(err));
这将起作用,并将结果存储在test.txt文件中,该文件将位于同一目录中
fs.readdirSync(__dirname).forEach(file => {
fs.appendFileSync("test.txt", file+"\n", function(err){
})
})
试试这个,它对我有用
import fs from "fs/promises";
const path = "path/to/folder";
export const readDir = async function readDir(path) {
const files = await fs.readdir(path);
// array of file names
console.log(files);
}
您可以使用fs.readdir或fs.readderSync方法。fs包含在Node.js核心中,因此不需要安装任何东西。
fs.加法器
const testFolder = './tests/';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
console.log(file);
});
});
fs.readder同步
const testFolder = './tests/';
const fs = require('fs');
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
});
这两种方法的区别在于,第一种方法是异步的,因此您必须提供一个回调函数,该函数将在读取过程结束时执行。
第二个是同步的,它将返回文件名数组,但它将停止代码的任何进一步执行,直到读取过程结束。
下面是一个仅使用本机fs和路径模块的简单解决方案:
// sync version
function walkSync(currentDirPath, callback) {
var fs = require('fs'),
path = require('path');
fs.readdirSync(currentDirPath).forEach(function (name) {
var filePath = path.join(currentDirPath, name);
var stat = fs.statSync(filePath);
if (stat.isFile()) {
callback(filePath, stat);
} else if (stat.isDirectory()) {
walkSync(filePath, callback);
}
});
}
或异步版本(改用fs.readder):
// async version with basic error handling
function walk(currentDirPath, callback) {
var fs = require('fs'),
path = require('path');
fs.readdir(currentDirPath, function (err, files) {
if (err) {
throw new Error(err);
}
files.forEach(function (name) {
var filePath = path.join(currentDirPath, name);
var stat = fs.statSync(filePath);
if (stat.isFile()) {
callback(filePath, stat);
} else if (stat.isDirectory()) {
walk(filePath, callback);
}
});
});
}
然后您只需调用(同步版本):
walkSync('path/to/root/dir', function(filePath, stat) {
// do something with "filePath"...
});
或异步版本:
walk('path/to/root/dir', function(filePath, stat) {
// do something with "filePath"...
});
不同之处在于节点在执行IO时如何阻塞。考虑到上面的API是相同的,您可以只使用异步版本来确保最大性能。
然而,使用同步版本有一个优点。在遍历完成后立即执行一些代码更容易,就像在遍历后的下一条语句中一样。对于异步版本,您需要一些额外的方法来知道何时完成。也许首先创建所有路径的映射,然后枚举它们。对于简单的build/util脚本(与高性能web服务器相比),您可以使用同步版本而不会造成任何损坏。