![](/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.