我试图使用Node.js获取目录中所有文件的名称列表。我希望输出文件名数组。我该怎么做?
当前回答
我最近为此开发了一个工具,它可以做到这一点。。。它异步获取目录并返回项目列表。您可以获取目录、文件或两者,首先是文件夹。如果不想获取整个文件夹,也可以对数据进行分页。
https://www.npmjs.com/package/fs-browser
这是链接,希望它能帮助到某人!
其他回答
非递归版本
您并没有说要递归地执行,所以我假设您只需要目录的直接子级。
示例代码:
const fs = require('fs');
const path = require('path');
fs.readdirSync('your-directory-path')
.filter((file) => fs.lstatSync(path.join(folder, file)).isFile());
采用@湖南罗斯托米扬的一般方法,使其更加简洁,并添加了excludeDirs论点。使用includeDirs进行扩展很简单,只需遵循相同的模式:
import * as fs from 'fs';
import * as path from 'path';
function fileList(dir, excludeDirs?) {
return fs.readdirSync(dir).reduce(function (list, file) {
const name = path.join(dir, file);
if (fs.statSync(name).isDirectory()) {
if (excludeDirs && excludeDirs.length) {
excludeDirs = excludeDirs.map(d => path.normalize(d));
const idx = name.indexOf(path.sep);
const directory = name.slice(0, idx === -1 ? name.length : idx);
if (excludeDirs.indexOf(directory) !== -1)
return list;
}
return list.concat(fileList(name, excludeDirs));
}
return list.concat([name]);
}, []);
}
示例用法:
console.log(fileList('.', ['node_modules', 'typings', 'bower_components']));
您可以使用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);
});
这两种方法的区别在于,第一种方法是异步的,因此您必须提供一个回调函数,该函数将在读取过程结束时执行。
第二个是同步的,它将返回文件名数组,但它将停止代码的任何进一步执行,直到读取过程结束。
这将起作用,并将结果存储在test.txt文件中,该文件将位于同一目录中
fs.readdirSync(__dirname).forEach(file => {
fs.appendFileSync("test.txt", file+"\n", function(err){
})
})
IMO完成此类任务最方便的方法是使用glob工具。这是node.js的glob包
npm install glob
然后使用通配符匹配文件名(示例取自软件包的网站)
var glob = require("glob")
// options is optional
glob("**/*.js", options, function (er, files) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// er is an error object or null.
})
如果您计划使用globby,这里有一个示例来查找当前文件夹下的任何xml文件
var globby = require('globby');
const paths = await globby("**/*.xml");
推荐文章
- 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和公共文件夹中的图像