javascript - fs.readdir 和 fs.readfile 和正则表达式

标签 javascript regex node.js

这是一个 Node 应用程序,运行 Express 服务器。我有一个包含文本文件的文件夹。我需要能够进入文件夹内的每个文件,并提取包含单词“SAVE”的行。

我被困在这一步了。

app.get('/logJson', function (req, res) {
  const logsFolder = 'C:/logs/';
  fs.readdir(logsFolder, (err, files) => {
    if (err) {
      res.send("[empty]");
      return;
    }
    files.forEach(function(filename){
      var logFiles = fs.readFileSync (logsFolder + filename, 'ascii').toString().split("\n");
      console.log(logFiles + "\n");
    })
  })
})

我不知道该将其包含在哪里:

var log = (logFiles.split(/.*SAVE.*/g)||['no result found'])[0];

如有任何帮助,我们将不胜感激

最佳答案

如果你只想打印出包含单词SAVE的所有行,你可以这样做。

备注:我没有运行此代码。

app.get('/logJson', function (req, res) {
  const logsFolder = 'C:/logs/';
  fs.readdir(logsFolder, (err, files) => {
    if (err) {
      res.send("[empty]");
      return;
    }
    var lines = [];
    files.forEach(function(filename) {
      var logFileLines = fs.readFileSync (logsFolder + filename, 'ascii').toString().split("\n");

      // go through the list of logFileLines
      logFileLines.forEach(function(logFileLine) {

        // if the current line matches SAVE, it will be stored in the variable lines
        if(logFileLine.match(/SAVE/)) {
          lines.push(logFileLine);
        }
      })
    })

    // the variable lines is printed to the console
    console.log(lines);
  })
})

关于javascript - fs.readdir 和 fs.readfile 和正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41452988/

相关文章:

javascript - 使用 onkeydown 或 onkeyup 浏览表 TR

c# - 需要 Regex 上的一个 block 是可选的

java - 匹配字符之间的文本(避免嵌套)

node.js - strapi 开始 : "url is not defined" - using mlab mongo DB

node.js - 抛出新错误 ('Missing PFX or certificate + private key' )

javascript - 在 node/express 中解析 bool 查询字符串参数的正确方法

javascript - Parse.com 云代码 RSA 验证 - Android 应用内购买验证

Javascript:如何通过异步递归树遍历控制流?

javascript - 如何使用客户端 gmail API 发送电子邮件,其中包含 html 内容和图像作为附件

javascript - 正则表达式允许输入字段中有 4 个数字(任意长度)