[英]How to get matched string from file using file System and nodejs?
I am passing string from client side and if that string is part of that file content i want to print that line , is it doable using fs and nodejs ? 我正在从客户端传递字符串,如果该字符串是该文件内容的一部分,我想打印该行,则可以使用fs和nodejs吗?
searvice.js 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;
You have first to split data
by new lines. 您必须首先用新行分割
data
。 Try this: 尝试这个:
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
}
});
}
Note: instead of making searchStr
global, you could just pass it as parametter to inspectFile
. 注意:您可以将其作为参数传递给
inspectFile
,而不是将searchStr
设置为inspectFile
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.