【发布时间】:2021-05-22 06:11:18
【问题描述】:
我想知道如何搜索所有文件,
如果找到关键字testsample,
然后控制台在nodejs中记录路径名,
如何读取和搜索关键字,在nodejs中显示路径
//app.js
var app = express();
var express = require('express');
var router = express.Router();
const path = require('path');
const fs = require('fs');
const directoryPath = path.join(__dirname, 'public');
fs.readdir(directoryPath, function (err, files) {
if (err) {
return console.log('Unable to scan directory: ' + err);
}
files.forEach(function (file) {
console.log(file);
});
});
假设目录结构是这样的
/path/to/your/dir
- dir1
- module1
- file1.js
- dir2
- anotherdir
- another_dir1
- index.js
- index.js
- index.js
- dir3
- file2.js
Expected Output
below path contains the keyword
/path/to/your/dir/dir1/module1/file1.js
/path/to/your/dir/dir2/anotherdir/another_dir1/index.js
/path/to/your/dir/dir2/anotherdir/index.js
/path/to/your/dir/dir2/index.js
/path/to/your/dir/dir3/file2js
【问题讨论】:
-
这个问题已经解决了数千次。一个简单的搜索会在这里找到许多代码示例和 NPM 上的许多模块为您执行此操作。如果您自己编写,请检查从
readdir()获得的每个条目,如果是目录,则递归到它。 -
@jfriend00 你能帮忙吗,
-
编程工具
grep应该可以做到这一点。
标签: javascript node.js arrays object fs