我试图使用Node.js获取目录中所有文件的名称列表。我希望输出文件名数组。我该怎么做?
当前回答
如果有人:
只想列出项目本地子文件夹中的文件名(不包括目录)
✅ 无其他依赖项✅ 1功能✅ 规格化路径(Unix与Windows)
const fs = require("fs");
const path = require("path");
/**
* @param {string} relativeName "resources/foo/goo"
* @return {string[]}
*/
const listFileNames = (relativeName) => {
try {
const folderPath = path.join(process.cwd(), ...relativeName.split("/"));
return fs
.readdirSync(folderPath, { withFileTypes: true })
.filter((dirent) => dirent.isFile())
.map((dirent) => dirent.name.split(".")[0]);
} catch (err) {
// ...
}
};
README.md
package.json
resources
|-- countries
|-- usa.yaml
|-- japan.yaml
|-- gb.yaml
|-- provinces
|-- .........
listFileNames("resources/countries") #=> ["usa", "japan", "gb"]
其他回答
使用flatMap:
function getFiles(dir) {
return fs.readdirSync(dir).flatMap((item) => {
const path = `${dir}/${item}`;
if (fs.statSync(path).isDirectory()) {
return getFiles(path);
}
return path;
});
}
给定以下目录:
dist
├── 404.html
├── app-AHOLRMYQ.js
├── img
│ ├── demo.gif
│ └── start.png
├── index.html
└── sw.js
用法:
getFiles("dist")
输出:
[
'dist/404.html',
'dist/app-AHOLRMYQ.js',
'dist/img/demo.gif',
'dist/img/start.png',
'dist/index.html'
]
我的单行代码:
const fs = require("fs")
const path = 'somePath/'
const filesArray = fs.readdirSync(path).filter(file => fs.lstatSync(path+file).isFile())
与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));
我通常使用:FS Extra。
const fileNameArray = Fse.readdir('/some/path');
结果:
[
"b7c8a93c-45b3-4de8-b9b5-a0bf28fb986e.jpg",
"daeb1c5b-809f-4434-8fd9-410140789933.jpg"
]
这是一个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
}
推荐文章
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- “node_modules”文件夹应该包含在git存储库中吗
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 使用package.json在全局和本地安装依赖项
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- this.libOptions.parse不是一个函数
- ReactJS和公共文件夹中的图像