Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,31 @@ Will output:
{ hello: 'world' }
```

If invalid JSON gets written, it's silently ignored.
If invalid JSON gets written, it's ignored.

You can listen to 'parsefail' event on the stream to get the lines that failed to parse.

```js
var JSONStream = require('json-stream');

var stream = JSONStream();

stream.on('data', function (chunk) {
console.dir(chunk);
});
stream.on('parsefail', function (chunk) {
console.dir('!!'+chunk);
});
stream.write('{"a":');
stream.write('42}\n');
stream.write('{"hel');
stream.write('lo": "world"}\n');
stream.write('not json\n');
```

Will output:
```
{ a: 42 }
{ hello: 'world' }
!!not json
```
9 changes: 7 additions & 2 deletions lib/json-stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,15 @@ JSONStream.prototype._transform = function (data, encoding, callback) {
while (++ptr <= data.length) {
if (data[ptr] === 10 || ptr === data.length) {
var line;
var slice = data.slice(start, ptr)
try {
line = JSON.parse(data.slice(start, ptr));
line = JSON.parse(slice);
}
catch (ex) {
if (data[ptr] === 10){
this.emit('parsefail', slice)
}
}
catch (ex) { }
if (line) {
this.push(line);
line = null;
Expand Down
21 changes: 21 additions & 0 deletions test/json-stream-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,22 @@ function expect(stream, events) {
});
}

function expectSideEffect(stream, evnetName, events) {
var lines = [], endCalled = false;
stream.on(evnetName, function (line) {
if (line) {
lines.push(line.toString());
}
});
stream.on('end', function () {
endCalled = true;
});
process.on('exit', function () {
assert.deepEqual(lines, events);
assert(endCalled);
});
}

var stream = JSONStream();
expect(stream, [ { a: 42 } ]);
write(stream, '{"a": 42}\n');
Expand All @@ -37,6 +53,11 @@ stream = JSONStream();
expect(stream, [ { a: 42 } ]);
write(stream, '{"a":', '42}\n');

stream = JSONStream();
expect(stream, [ { a: 42 } ]);
expectSideEffect(stream, 'parsefail', [ 'blah' ]);
write(stream, '{"a":', '42}\n','blah\n');

stream = JSONStream();
expect(stream, [ { a: 42, b: 1337 } ]);
write(stream, '{"a":', '42', ',"b": 1337', '}\n');
Expand Down