【问题标题】:How to list the path filename in nodejs如何在nodejs中列出路径文件名
【发布时间】: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


【解决方案1】:

应该这样做!!


const path = require('path');
const fs = require('fs');
const directoryPath = path.join(__dirname, 'Documents');
fs.readdir(directoryPath, function (err, files) {
    //handling error
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    }   
    files.forEach(function (file) {
        console.log(file); 
    });
});

【讨论】:

  • 谢谢回复,代码我用过,不知道如何查看文件中的关键字并列出路径,
  • 您想根据搜索词过滤文件名??因为如果没有文件的任何元数据,将无法进行关键字搜索
猜你喜欢
  • 2016-01-17
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多