Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search stream for string in node.js?

How does one search for a string in a stream and then print it? By this I mean with the use of createReadStream. I figured out how to find strings in readFile with the use of indexOf, but I am reading that using streams are more efficient.

More specifically, I've been trying to find a string within a stream, and then print out the whole line that contains the string. However the following keeps giving me errors

fs.createReadStream(process.argv[2], function (err, data) {
      data.indexOf ...

Currently, my program prints out the entire stream rather than just the lines containing the strings.

var http = require('http'); 
var fs = require('fs');

var server = http.createServer( function(req, res) {

console.log("Request received.");

res.writeHead(200, {"Content-Type": "text/plain"});
res.write("Hello World\n\n\n");

var s = fs.createReadStream(process.argv[2]).pipe(res); 

s.on('end', function(){ res.end() }) 


});
server.listen(8000);
like image 470
krikara Avatar asked Mar 25 '26 11:03

krikara


1 Answers

Streams are buffered, so the buffers passed to the data event (which you would normally listen to) aren't in any way split into, or delimited on, separate lines.

You can use the readline module to perform line-by-line searching:

var fs        = require('fs');
var readline  = require('readline');

var server = http.createServer( function(req, res) {
  console.log("Request received.");

  res.writeHead(200, {"Content-Type": "text/plain"});
  res.write("Hello World\n\n\n");

  readline.createInterface({
    input     : fs.createReadStream(process.argv[2]),
    terminal  : false
  }).on('line', function(line) {
    var idx = line.indexOf(THE_SUBSTRING);
    if (idx !== -1) {
      res.write(line + '\n');
    }
  }).on('close', function() {
    res.end();
  });
});

(EDIT: readline strips newlines, so res.write adds one back)

like image 127
robertklep Avatar answered Mar 26 '26 23:03

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!