![](/img/trans.png)
[英]Get all files within a folder containing string, push filenames to array and return array using Node FS
[英]How to search for files by extension and containing string within folder and subfolders?
是否可以通過提供的包含字符串查找給定擴展名的文件?
我的方法應該是什么? 例如,輸入是txt
和hello
,output 將是包含字符串hello
且擴展名為txt
的所有文件的列表。
您可以使用FileSystem通過readdir
方法獲取文件夾的內容,這將返回一個字符串數組。
假設您的工作目錄是一個src
文件,其中有一個要讀取的files
夾。 您的腳本如下所示:
const fs = require('fs');
var files = fs.readdir('./files', (err, filenames) => {
if (err) throw err;
return filenames;
})
然后,您可以使用字符串方法分隔字符串。 假設您要擁有兩個變量, fileName
和fileExt
您將使用String.split(separator)
方法,並使用.
字符作為分隔符。
var files = // fs snippet above
for (file in files) {
let fileComponents = file.split('.');
let fileName = fileComponents[0];
let fileExt = fileComponents[1];
// You can run your code on the name, and extension of your file here.
}
這不適用於名稱中包含多個點的文件。 您將需要對數組進行額外的工作,以確保fileName
包含每個連接的字符串,並用分隔.
直到您的fileComponents
字符串的最終索引
你會在你的終端寫這個: node main.js hello
對於給定的目錄,它將在所有子目錄和所有文件中搜索帶有hello
的文本文件
這是代碼:
const { readdirSync, readFileSync, lstatSync } = require('fs');
const path = require('path');
const getDir = source => {
const results = readdirSync(source);
results.forEach(function (result) {
if (lstatSync(path.join(source, result))
.isFile()) {
if (readFileSync(path.join(source, result))
.includes(argument) && path.extname(result)
.toLowerCase() === extension) {
console.log("Your string is is in file: ", result)
}
}
else if (lstatSync(path.join(source, result))
.isDirectory()) {
getDir(path.join(source, result));
}
});
}
const dir = process.cwd();
const extension = '.txt'; //You can change the extension type here
let argument = process.argv[2];
getDir(dir);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.