Javascript 如何使用 node.js 获取具有特定文件扩展名的文件列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44199883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get a list of files with specific file extension using node.js?
提问by Bjorn Reppen
The node fspackage has the following methods to list a directory:
node fs包有以下列出目录的方法:
fs.readdir(path, [callback])Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.
fs.readdirSync(path)Synchronous readdir(3). Returns an array of filenames excluding '.' and '..
fs.readdir(path, [callback])异步 readdir(3)。读取目录的内容。回调获取两个参数(err、files),其中 files 是目录中文件名称的数组,不包括 '.' 和 '..'。
fs.readdirSync(path)同步 readdir(3)。返回不包括“.”的文件名数组 和 '..
But how do I get a list of files matching a file specification, for example *.txt?
但是如何获取与文件规范匹配的文件列表,例如*.txt?
回答by Freeman Lambda
You could filter they array of files with an extension extractor function. The pathmodule provides one such function, if you don't want to write your own string manipulation logic or regex.
您可以使用扩展提取器功能过滤它们的文件数组。path如果您不想编写自己的字符串操作逻辑或正则表达式,该模块提供了一个这样的功能。
var path = require('path');
var EXTENSION = '.txt';
var targetFiles = files.filter(function(file) {
return path.extname(file).toLowerCase() === EXTENSION;
});
EDITAs per @arboreal84's suggestion, you may want to consider cases such as myfile.TXT, not too uncommon. I just tested it myself and path.extnamedoes not do lowercasing for you.
编辑根据@arboreal84 的建议,您可能需要考虑诸如myfile.TXT,并不太罕见的情况。我只是自己测试过,path.extname并没有为你做小写。
回答by Lazyexpert
Basically, you do something like this:
基本上,你做这样的事情:
const path = require('path')
const fs = require('fs')
const dirpath = path.join(__dirname, '/path')
fs.readdir(dirpath, function(err, files) {
const txtFiles = files.filter(el => /\.txt$/.test(el))
// do something with your files, by the way they are just filenames...
})
回答by Cruiser KID
fsdoesn't support filtering itself but if you don't want to filter youself then use glob
fs不支持过滤本身,但如果你不想过滤自己然后使用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.
})
回答by Abdul Samad
I used the following code and its working fine:
我使用了以下代码并且它工作正常:
var fs = require('fs');
var path = require('path');
var dirPath = path.resolve(__dirname); // path to your directory goes here
var filesList;
fs.readdir(dirPath, function(err, files){
filesList = files.filter(function(e){
return path.extname(e).toLowerCase() === '.txt'
});
console.log(filesList);
});

