javascriptnode.jsjsonstream

Basic test of JSONStream not working


I'm having a look at JSONStream in node.js, and I'm trying the following small app to get a handle on it:

var JSONStream = require('JSONStream');
var Stream = require('stream');

var s = new Stream();
s.pipe = function(dest) {
  dest.write('{"foo":1}');
  return dest;
};

var parser = JSONStream.parse(/foo/);
s.pipe(parser).pipe(process.stdout);

Unfortunately, when run on the commandline, this doesn't write anything to the console. What am I doing wrong?


Solution

  • It works if you rewrite your code:

    var JSONStream = require('JSONStream');
    var Stream = require('stream');
    
    var s = new Stream();
    s.pipe = function(dest) {
      dest.write('{"foo":1}');
      return dest;
    };
    
    var parser = JSONStream.parse();
    parser.on('data', function(obj) {
      console.log('obj', obj);
    });
    s.pipe(parser);
    

    The reason you can't pipe the output of JSONStream.parse() to process.stdout is that JSONStream outputs objects, and process.stdout only accepts strings (and probably Buffers):

    > process.stdout.write({ foo : 1 });
    TypeError: invalid data
        at WriteStream.Socket.write (net.js:612:11)
        ...