![](/img/trans.png)
[英]Using Node.JS, how do you get a list of files in chronological order?
[英]How do I get a list of files with specific file extension using node.js?
node fs包有以下列出目录的方法:
fs.readdir(path, [callback])异步 readdir(3)。 读取目录的内容。 回调获取两个参数(err、files),其中 files 是目录中文件名称的数组,不包括 '.' 和 '..'。
fs.readdirSync(path)同步 readdir(3)。 返回不包括“.”的文件名数组和 '..
但是如何获取与文件规范匹配的文件列表,例如*.txt ?
您可以使用扩展名提取器功能过滤它们的文件数组。 如果您不想编写自己的字符串操作逻辑或正则表达式, path
模块提供了一个这样的功能。
const path = require('path');
const EXTENSION = '.txt';
const targetFiles = files.filter(file => {
return path.extname(file).toLowerCase() === EXTENSION;
});
编辑根据@arboreal84 的建议,您可能需要考虑诸如myfile.TXT
,并不少见。 我只是自己测试过, path.extname
不会为你做小写。
基本上,你做这样的事情:
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 => path.extname(el) === '.txt')
// do something with your files, by the way they are just filenames...
})
我使用了以下代码并且它工作正常:
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);
});
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.
})
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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.