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

时间:2017-02-24 20:07:13

标签: javascript node.js fs

我从客户端传递字符串,如果该字符串是该文件内容的一部分,我想打印该行,是否可以使用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;

1 个答案:

答案 0 :(得分:1)

您首先要按新行分割import sys glory = input("Glory charge: ") glory_prev = glory print(glory_prev) pouch = 28 run_num = 0 nat_price = input("Nat price: ") while True: run = input("You've done " + (str(run_num)) + " runs: ") if run == "a": glory = glory - 1 pouch -= 1 if glory == 0: print("New glory needed") glory = glory_prev if pouch == 0: print("Repair pouch") pouch = 28 elif run == "q": sys.exit else: continue 。试试这个:

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