如何使用文件系统和nodejs从文件中获取匹配的字符串?

How to get matched string from file using file System and nodejs?

我从客户端传递字符串,如果该字符串是该文件内容的一部分,我想打印该行,使用 fs 和 nodejs 是否可行?

searvice.js

var fs = require('fs');
var path = require('path');
var async = require('async');
var searchStr;

function readFile(str){
    searchStr = str;
//  var url = './logs/St/server1.log';
    fs.readFile('./logs/St/server1.log', 'utf8', function (err,data) {
      if (err) {
        return console.log(err);
      }
      console.log('Server Data',data);
      inspectFile(data);
    });
}


function inspectFile(data) {
    if (data.indexOf(searchStr) != -1) {
        // do something
        console.log('print the matching data');
    }
}

exports.readFile = readFile;

您必须先用新行拆分 data。试试这个:

function inspectFile(data) {
    var lines = data.split('\n');              // get the lines
    lines.forEach(function(line) {             // for each line in lines
        if(line.indexOf(searchStr) != -1) {    // if the line contain the searchStr
            console.log(line);                 // then log it
        }
    });
}

注意: 而不是使 searchStr 全局化,您可以将它作为参数传递给 inspectFile