如何使用node.js获取具有特定文件扩展名的文件列表?

Bjo*_*pen 12 javascript node.js

节点fs包具有以下列出目录的方法:

fs.readdir(path,[callback])异步readdir(3).读取目录的内容.回调有两个参数(错误,文件),其中files是目录中文件名的数组,不包括'.' 和'..'.

fs.readdirSync(path)同步readdir(3).返回不包含'.'的文件名数组 和'..

但是如何获得与文件规范匹配的文件列表,例如*.txt

Fre*_*bda 22

您可以使用扩展提取器函数过滤它们的文件数组.path如果您不想编写自己的字符串操作逻辑或正则表达式,则该模块提供了一个此类函数.

var path = require('path');

var EXTENSION = '.txt';

var targetFiles = files.filter(function(file) {
    return path.extname(file).toLowerCase() === EXTENSION;
});
Run Code Online (Sandbox Code Playgroud)

编辑 根据@ arboreal84的建议,你可能想要考虑这样的情况myfile.TXT,并不太常见.我只是自己测试过,path.extname不会为你做小写.

  • 几乎正确。您需要小写扩展名,因为某些文件可能使用大写形式,例如:.TXT (2认同)
  • 对于进行复制/粘贴的人来说,这个答案缺少目录的实际读取,这就是 Lazyexpert 答案的情况 (2认同)

Laz*_*ert 10

基本上,你做这样的事情:

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...
})
Run Code Online (Sandbox Code Playgroud)

  • 不要使用正则表达式解析文件名,请使用`path.extname`。 (2认同)
  • 我同意,在某些复杂的情况下,这都是真的。但说实话,这个:`/\.txt$/`,需要时间来阅读和理解吗? (2认同)
  • 你可以写‘1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1’,就是10。每个人都会加吧?它的复杂度为0?但这对读者来说是**浪费时间**。只需写“10”即可。必须在头脑中计算总和会分散读者的注意力,使他们无法理解“10”如何适应代码的其余部分。 (2认同)

Abd*_*mad 6

我使用了以下代码并且它工作正常:

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);
});
Run Code Online (Sandbox Code Playgroud)


Cru*_*KID 5

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.
})
Run Code Online (Sandbox Code Playgroud)