[英]How to search for files by extension and containing string within folder and subfolders?
Is it possible to look for files of given extension by the containing string provided?是否可以通过提供的包含字符串查找给定扩展名的文件?
What should my approach be?我的方法应该是什么? For example the input is
txt
and hello
, and the output will be list of all files containing the string hello
with extension txt
.例如,输入是
txt
和hello
,output 将是包含字符串hello
且扩展名为txt
的所有文件的列表。
You can use FileSystem to get the contents of a folder with the readdir
method, this returns you an array of strings. 您可以使用FileSystem通过
readdir
方法获取文件夹的内容,这将返回一个字符串数组。
Let's say your working directory is a src
file, in which there is a files
folder that you want to read. 假设您的工作目录是一个
src
文件,其中有一个要读取的files
夹。 Your script would look something like this: 您的脚本如下所示:
const fs = require('fs');
var files = fs.readdir('./files', (err, filenames) => {
if (err) throw err;
return filenames;
})
You can then separate your string using string methods. 然后,您可以使用字符串方法分隔字符串。 Let's say you want to have two variables,
fileName
and fileExt
You would use the String.split(separator)
method, and use the .
假设您要拥有两个变量,
fileName
和fileExt
您将使用String.split(separator)
方法,并使用.
character as 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.
}
This will not work for files containing multiple dots in their name. 这不适用于名称中包含多个点的文件。 You will need extra work on the array to make sure
fileName
contains every string concatenated, separated by a .
您将需要对数组进行额外的工作,以确保
fileName
包含每个连接的字符串,并用分隔.
up until the final index of your fileComponents
string 直到您的
fileComponents
字符串的最终索引
You would write this in your terminal: node main.js hello
你会在你的终端写这个:
node main.js hello
For a given directory it will search inside all subdirectories and all files for a text file with hello
对于给定的目录,它将在所有子目录和所有文件中搜索带有
hello
的文本文件
Here is the code:这是代码:
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.