pax_global_header00006660000000000000000000000064152245545120014517gustar00rootroot0000000000000052 comment=1ad1306340f530336fb3044c0a4ebce78a00f3ab pixl-json-stream-1.0.10/000077500000000000000000000000001522455451200150125ustar00rootroot00000000000000pixl-json-stream-1.0.10/.npmignore000066400000000000000000000000311522455451200170030ustar00rootroot00000000000000.gitignore node_modules/ pixl-json-stream-1.0.10/README.md000066400000000000000000000214251522455451200162750ustar00rootroot00000000000000# Overview This module provides a convenient way to send/receive complex data objects over streams (pipes and sockets). It does this by transparently serializing the data to JSON, and parsing it on the other side, emitting a `json` event to your code whenever it has a complete JSON message. The library handles all buffering for you, and so it will only emit one `json` event for each completed JSON document, pre-parsed into a data object for your callback. And for sending data, you can pass it a complex object, which will be auto-serialized and streamed over the pipe or socket. # Usage Use [npm](https://www.npmjs.com/) to install the module: ``` npm install pixl-json-stream ``` Then use `require()` to load it in your code: ```javascript const JSONStream = require('pixl-json-stream'); ``` To use the module, instantiate an object, and attach it to a stream: ```javascript let stream = new JSONStream( read_stream, write_stream ); ``` Network sockets are both read and write, so you only need to pass in one argument for those: ```javascript let stream = new JSONStream( socket_handle ); ``` You can then add a listener for the `json` event to receive a fully parsed JSON document, or call `write()` to send one. Example: ```javascript stream.on('json', function(data) { console.log("Got data: ", data); } ); stream.write({ action: "something", code: 1234 }); ``` You will always receive pre-parsed JSON as a data object, and `write()` handles all serialization for you as well. So you never have to call `JSON.parse()` or `JSON.stringify()` directly. ## Use With Child Processes Here is a more complete example, which attaches a read/write JSON stream to a child process, sets up a read listener, and writes to the child: ```javascript const JSONStream = require('pixl-json-stream'); // spawn worker process let child = require('child_process').spawn( 'node', ['my-worker.js'], { stdio: ['pipe', 'pipe', 'pipe'] } ); // connect json stream to child's stdio // (read from child.stdout, write to child.stdin) let stream = new JSONStream( child.stdout, child.stdin ); stream.on('json', function(data) { // received data from child console.log("Got data from child: ", data); } ); // write data to child stream.write({ action: 'update_user_record', username: 'jhuckaby', other: 12345 }); // close child's stdin so it can exit normally child.stdin.end(); ``` You can also use a JSON stream in the child process itself, to handle the other side of the pipe: ```javascript const JSONStream = require('pixl-json-stream'); let stream = new JSONStream( process.stdin, process.stdout ); stream.on('json', function(data) { // got data from parent, send something back stream.write({ code: 0, description: "Success from child" }); } ); ``` ## Use With Network Sockets You can also use JSON streams over network sockets, providing an easy way to send structured data to/from your clients and servers. For example, on the server side you could have: ```javascript let server = require('net').createServer(function(socket) { // new connection, attach JSON stream handler let stream = new JSONStream(socket); stream.on('json', function(data) { // got gata from client console.log("Received data from client: ", data); // send response stream.write({ code: 1234, description: "We hear you" }); } ); }); server.listen( 3012 ); ``` And on the client side... ```javascript let client = require('net').connect( {port: 3012}, function() { // connected to server, now use JSON stream to communicate let stream = new JSONStream( client ); stream.on('json', function(data) { // got response back from server console.log("Received response from server: ", data); } ); // send greetings stream.write({ code: 2345, description: "Hello from client!" }); } ); ``` ## Matching JSON records By default, the library recognizes JSON documents on lines using the following regular expression: ```js /^\s*\{/ ``` This is a very loose pattern match, designed to be performant (i.e. it only matches up to the first opening curly brace, and then assumes the entire line is JSON). However, if you would like this to be more strict and/or exact, you can change the pattern by setting the `recordRegExp` property on your stream instance, and set it to a custom regular expression of your choice. Here is an example of this: ```js let stream = new JSONStream( process.stdin, process.stdout ); stream.recordRegExp = /^\s*\{.+\}\s*$/; ``` This would match both opening and closing curly braces on a line. While this is slower, it is more exact and would only match full JSON documents on a line. ## Catching Non-JSON Text When the library detects non-JSON lines, it emits a `text` event. You can capture these and handle them how you see fit. Example: ```js let stream = new JSONStream( process.stdin, process.stdout ); stream.on('text', function(text) { // got a line of text that is not JSON } ); ``` ### Preserving Whitespace The library will by default skip lines of text that are purely whitespace (e.g. blank empty lines). If you would like to change this behavior, set the `preserveWhitespace` property to true. Then you will receive **all** the raw `text` events regardless of their content. Example: ```js let stream = new JSONStream( process.stdin, process.stdout ); stream.preserveWhitespace = true; ``` ## End of Lines By default, the library assumes each JSON record will be delimited by the current operating system's end-of-line character sequence ([os.EOL](https://nodejs.org/api/os.html#os_os_eol)), which is `\n` on Unix/Linux/OSX. However, you can change this by setting the `EOL` string property on your class instance: ```js let stream = new JSONStream( process.stdin, process.stdout ); stream.EOL = "\r\n"; // DOS line endings ``` ## Maximum Line Length The library has an "emergency brake" which kicks in if a single line grows beyond 2 MB (1,048,576 UTF-16 characters) by default. This is to prevent a runaway memory situation. If this limit is reached, the line is truncated *from the end*. The idea here is to better handle cases where terminal or script output has overwriting lines (i.e. using `/r` carriage returns), where the most important information will probably be towards the end of the buffer. To customize the line limit, set the `maxLineLength` property on your stream instance. Example: ```js let stream = new JSONStream( process.stdin, process.stdout ); stream.maxLineLength = 1024 * 1024; ``` Note that JavaScript strings are interally encoded in UTF-16, so each character takes up 2 bytes of RAM. ## Performance Tracking If you happen to use our [pixl-perf](https://www.github.com/jhuckaby/pixl-perf) module in your application, you can pass in a performance tracker by calling `setPerf()` on a JSON Stream. Example: ```js let stream = new JSONStream( process.stdin, process.stdout ); stream.setPerf( perf ); ``` This will track the total JSON parse time, the JSON compose time, and the JSON payload sizes on both reads and writes. Also, if any stream `write()` calls happen to return `false` (i.e. buffered), a special `json_stream_write_buffer` perf counter is incremented. Here are all the performance tracking keys used: | Perf Key | Type | Description | |----------|------|-------------| | `json_stream_parse` | Elapsed Time | Time spent parsing JSON. | | `json_stream_compose` | Elapsed Time | Time spent composing JSON. | | `json_stream_bytes_read` | Counter | Number of bytes read from stream. | | `json_stream_bytes_written` | Counter | Number of bytes written to stream. | | `json_stream_msgs_read` | Counter | Number of JSON messages read from stream. | | `json_stream_msgs_written` | Counter | Number of JSON messages written to stream. | | `json_stream_write_buffer` | Counter | Number of times the stream `write()` call returned `false`. | # License **The MIT License** *Copyright (c) 2014 - 2026 Joseph Huckaby* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pixl-json-stream-1.0.10/json-stream.js000066400000000000000000000073501522455451200176170ustar00rootroot00000000000000// JSON Buffer Stream // Handles buffering JSON records over standard streams (pipes or sockets) // // Assumes one entire JSON document per line, delimited by EOL. // Emits 'json' event for each JSON document received. // Emits `text` event for each non-JSON line. // write() method accepts object to be JSON-stringified and written to stream. // Passes errors thru on 'error' event (with addition of JSON parse errors). // // Copyright (c) 2014 - 2026 Joseph Huckaby // Released under the MIT License var os = require('os'); var Class = require("pixl-class"); module.exports = Class.create({ streamIn: null, streamOut: null, buffer: '', perf: null, recordRegExp: /^\s*\{/, preserveWhitespace: false, maxLineLength: 1024 * 1024, EOL: os.EOL, __construct: function(stream_in, stream_out) { // class constructor if (!stream_out) stream_out = stream_in; this.streamIn = stream_in; this.streamOut = stream_out; this.init(); }, setPerf: function(perf) { this.perf = perf; }, init: function() { // hook stream read var self = this; this.streamIn.setEncoding('utf8'); this.streamIn.on('data', function(data) { if (self.buffer) { data = self.buffer + data; if (data.length > self.maxLineLength) data = data.substring( data.length - self.maxLineLength ); self.buffer = ''; } var endsOnEOL = (data.substring(data.length - self.EOL.length) == self.EOL); var records = data.split( self.EOL ); // if data ends on EOL, discard the trailing empty split item // otherwise, buffer the partial record for the next read if (endsOnEOL) { records.pop(); } else { self.buffer = records.pop(); } var record = ''; var json = null; for (var idx = 0, len = records.length; idx < len; idx++) { record = records[idx]; if (record.match(self.recordRegExp)) { json = null; if (self.perf) self.perf.begin('json_stream_parse'); try { json = JSON.parse(record); } catch (e) { self.emit('error', new Error("JSON Parse Error: " + e.message), record); } if (self.perf) { self.perf.end('json_stream_parse'); self.perf.count('json_stream_msgs_read', 1); self.perf.count('json_stream_bytes_read', record.length + self.EOL.length); } if (json) { self.emit('json', json); } } // record has json else if (self.preserveWhitespace || record.match(/\S/)) { // non-json garbage, emit text event just in case app cares // but only if (1) text has non-whitespace, or (2) preserveWhitespace is set var text = record + self.EOL; if (text.length) self.emit('text', text); } } // foreach record } ); // catch errors on both streams if (this.streamOut != this.streamIn) { // separate streams this.streamIn.on('error', function(err) { self.emit('error', "Error in input stream: " + err.message); } ); this.streamOut.on('error', function(err) { self.emit('error', "Error in output stream: " + err.message); } ); } else { // bi-directional stream this.streamIn.on('error', function(err) { self.emit('error', err); } ); } // catch end of stream this.streamIn.on('end', function() { self.emit('end'); } ); }, write: function(json, callback) { // write json data to stream plus EOL if (this.perf) this.perf.begin('json_stream_compose'); var data = JSON.stringify(json); if (this.perf) { this.perf.end('json_stream_compose'); this.perf.count('json_stream_msgs_written', 1); this.perf.count('json_stream_bytes_written', data.length + this.EOL.length); } var result = this.streamOut.write( data + this.EOL, callback ); if (!result && this.perf) { this.perf.count('json_stream_write_buffer', 1); } return result; } }); pixl-json-stream-1.0.10/package.json000066400000000000000000000012701522455451200173000ustar00rootroot00000000000000{ "name": "pixl-json-stream", "version": "1.0.10", "description": "Provides an easy API for sending and receiving JSON records over standard streams (pipes or sockets).", "author": "Joseph Huckaby ", "homepage": "https://github.com/jhuckaby/pixl-json-stream", "license": "MIT", "main": "json-stream.js", "repository": { "type": "git", "url": "https://github.com/jhuckaby/pixl-json-stream" }, "bugs": { "url": "https://github.com/jhuckaby/pixl-json-stream/issues" }, "scripts": { "test": "node test/test.js" }, "keywords": [ "json", "stream" ], "dependencies": { "pixl-class": "^1.0.3" }, "devDependencies": {} } pixl-json-stream-1.0.10/test/000077500000000000000000000000001522455451200157715ustar00rootroot00000000000000pixl-json-stream-1.0.10/test/test.js000066400000000000000000000066331522455451200173160ustar00rootroot00000000000000// Regression tests for stream chunk boundaries. // Run these using: npm test var assert = require('assert'); var PassThrough = require('stream').PassThrough; var JSONStream = require('../json-stream'); // Feed a parser the exact chunks supplied and capture its public events. function parseChunks(chunks, options) { var input = new PassThrough(); var parser = new JSONStream(input); var result = { text: [], json: [], events: [] }; options = options || {}; if (options.EOL) parser.EOL = options.EOL; parser.preserveWhitespace = !!options.preserveWhitespace; parser.on('text', function(text) { result.text.push(text); result.events.push({ type: 'text', data: text }); } ); parser.on('json', function(data) { result.json.push(data); result.events.push({ type: 'json', data: data }); } ); chunks.forEach(function(chunk) { input.write(chunk); } ); return result; } // Verify that every possible single split point produces identical output. function testEveryBoundary(data, expected, options) { for (var idx = 1; idx < data.length; idx++) { var result = parseChunks([ data.substring(0, idx), data.substring(idx) ], options); assert.deepStrictEqual(result.events, expected, 'failed at chunk boundary ' + idx); } // Also exercise the extreme case where every character is a separate chunk. var result = parseChunks(data.split(''), options); assert.deepStrictEqual(result.events, expected, 'failed with one character per chunk'); } // A chunk ending exactly on EOL should emit one complete text record. var result = parseChunks([ 'hello\n' ], { EOL: '\n' }); assert.deepStrictEqual(result.text, [ 'hello\n' ]); // A complete record before a partial tail must retain its EOL. result = parseChunks([ 'hello\nwor', 'ld\n' ], { EOL: '\n' }); assert.strictEqual(result.text.join(''), 'hello\nworld\n'); // Multiple complete records before a partial tail must all retain their EOL. result = parseChunks([ 'one\ntwo\nthr', 'ee\n' ], { EOL: '\n' }); assert.strictEqual(result.text.join(''), 'one\ntwo\nthree\n'); // Blank records are emitted only when whitespace preservation is enabled. result = parseChunks([ 'one\n\n', 'two\n' ], { EOL: '\n', preserveWhitespace: true }); assert.strictEqual(result.text.join(''), 'one\n\ntwo\n'); result = parseChunks([ 'one\n\n', 'two\n' ], { EOL: '\n', preserveWhitespace: false }); assert.strictEqual(result.text.join(''), 'one\ntwo\n'); // Preserve multiple consecutive blank lines without joining adjacent records. result = parseChunks([ 'one\n\n', '\nthree\n' ], { EOL: '\n', preserveWhitespace: true }); assert.strictEqual(result.text.join(''), 'one\n\n\nthree\n'); // A multi-character EOL may itself be split across chunks. result = parseChunks([ 'one\r', '\ntwo\r\n' ], { EOL: '\r\n' }); assert.strictEqual(result.text.join(''), 'one\r\ntwo\r\n'); // JSON event ordering must remain intact when followed by partial text. result = parseChunks([ '{"xy":1}\nhel', 'lo\n' ], { EOL: '\n' }); assert.deepStrictEqual(result.events, [ { type: 'json', data: { xy: 1 } }, { type: 'text', data: 'hello\n' } ]); // Exercise all single boundaries, including boundaries inside CRLF itself. testEveryBoundary('one\r\ntwo\r\n', [ { type: 'text', data: 'one\r\n' }, { type: 'text', data: 'two\r\n' } ], { EOL: '\r\n' }); testEveryBoundary('{"xy":1}\nhello\n', [ { type: 'json', data: { xy: 1 } }, { type: 'text', data: 'hello\n' } ], { EOL: '\n' }); console.log('All pixl-json-stream tests passed.');