poseid
poseid

Reputation: 7156

How to parse lines from a Buffer with streams?

So, I get a file stream from STDIN with line breaks, but the stream delivers buffers where the line breaks disappear.

How would I process/parse lines with the Stream approach?

util.inherits(Parser, Transform);

Parser.prototype._transform = function(data, encoding, done) {
  console.log(data.toString());
  this.push(this._parseRow(data));
  done();
};

// Parse a data row into an object
Parser.prototype._parseRow = function(row) {
  var result = row.toString().split("\r");
  var fields = result.toString().split(";");
  var bank = { a: fields[0], b: fields[1].trim() };
  return bank.toString();
};

But the output has line breaks randomly.

Upvotes: 2

Views: 1844

Answers (1)

arnorhs
arnorhs

Reputation: 10429

You can use the split module.

var split = require('split');
process.stdin.pipe(split()).pipe(process.stdout);

Note that split will actually remove the newlines, so you'll have to re-add them if you want to keep newlines.

Upvotes: 4

Related Questions