我试图使用Node.js获取目录中所有文件的名称列表。我希望输出文件名数组。我该怎么做?
当前回答
如果有人还在搜索这个,我会这样做:
从“fs”导入fs;从“path”导入路径;const getAllFiles=目录=>fs.readdirSync(dir).reduce((files,file)=>{常量名称=路径.连接(目录,文件);const isDirectory=fs.statSync(名称).isDirectory();return isDirectory?[…file,…getAllFiles(名称)]:[…files,名称];}, []);
它的工作对我很好
其他回答
它只有2行代码:
fs=require('fs')
fs.readdir("./img/", (err,filename)=>console.log(filename))
图像:
与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));
使用npm列表内容模块。它读取给定目录的内容和子内容,并返回文件和文件夹路径列表。
const list = require('list-contents');
list("./dist",(o)=>{
if(o.error) throw o.error;
console.log('Folders: ', o.dirs);
console.log('Files: ', o.files);
});
这是一个TypeScript,可选递归,可选错误日志和异步解决方案。可以为要查找的文件名指定正则表达式。
我使用了fs extra,因为这是对fs的一个简单的超集改进。
import * as FsExtra from 'fs-extra'
/**
* Finds files in the folder that match filePattern, optionally passing back errors .
* If folderDepth isn't specified, only the first level is searched. Otherwise anything up
* to Infinity is supported.
*
* @static
* @param {string} folder The folder to start in.
* @param {string} [filePattern='.*'] A regular expression of the files you want to find.
* @param {(Error[] | undefined)} [errors=undefined]
* @param {number} [folderDepth=0]
* @returns {Promise<string[]>}
* @memberof FileHelper
*/
public static async findFiles(
folder: string,
filePattern: string = '.*',
errors: Error[] | undefined = undefined,
folderDepth: number = 0
): Promise<string[]> {
const results: string[] = []
// Get all files from the folder
let items = await FsExtra.readdir(folder).catch(error => {
if (errors) {
errors.push(error) // Save errors if we wish (e.g. folder perms issues)
}
return results
})
// Go through to the required depth and no further
folderDepth = folderDepth - 1
// Loop through the results, possibly recurse
for (const item of items) {
try {
const fullPath = Path.join(folder, item)
if (
FsExtra.statSync(fullPath).isDirectory() &&
folderDepth > -1)
) {
// Its a folder, recursively get the child folders' files
results.push(
...(await FileHelper.findFiles(fullPath, filePattern, errors, folderDepth))
)
} else {
// Filter by the file name pattern, if there is one
if (filePattern === '.*' || item.search(new RegExp(filePattern, 'i')) > -1) {
results.push(fullPath)
}
}
} catch (error) {
if (errors) {
errors.push(error) // Save errors if we wish
}
}
}
return results
}
加载fs:
const fs = require('fs');
异步读取文件:
fs.readdir('./dir', function (err, files) {
// "files" is an Array with files names
});
读取文件同步:
var files = fs.readdirSync('./dir');