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

时间:2017-05-26 11:00:40

标签: javascript node.js

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

  

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

     

fs.readdirSync(path)同步readdir(3)。返回一个数组   文件名不包括'。'和'..

但是如何获得符合文件规范的文件列表,例如 * .txt

5 个答案:

答案 0 :(得分:16)

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

var path = require('path');

var EXTENSION = '.txt';

var targetFiles = files.filter(function(file) {
    return path.extname(file).toLowerCase() === EXTENSION;
});

修改的 根据@ arboreal84的建议,您可能需要考虑诸如myfile.TXT之类的情况,这并不常见。我自己测试了它,而path.extname并没有为你做小写。

答案 1 :(得分:6)

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

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...
})

答案 2 :(得分:2)

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

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);
});

答案 3 :(得分:1)

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.
})

答案 4 :(得分:1)

const fs = require('fs');
const path = require('path');
    
// Path to the directory(folder) to look into
const dirPath = path.resolve(`${__dirname}../../../../../tests_output`);
        
// Read all files with .txt extension in the specified folder above
const filesList = fs.readdirSync(dirPath, (err, files) => files.filter((e) => path.extname(e).toLowerCase() === '.txt'));
        
// Read the content of the first file with .txt extension in the folder
const data = fs.readFileSync(path.resolve(`${__dirname}../../../../../tests_output/${filesList[0]}`), 'utf8');
相关问题