1.0.1 • Published 7 years ago

ldjson-body v1.0.1

Weekly downloads
1
License
MIT
Repository
github
Last release
7 years ago

ldjson-body

Build status NPM version XO code style

Get a stream for a line delimited json response body in the browser, compatible with Fetch

Based on the JSON chunk parser from eBay's jsonpipe

Installation

Install ldjson-body using npm:

npm install --save ldjson-body

Usage

Module usage

const ldjsonBody = require('ldjson-body');

fetch('https://a.url.that.provides.linedelimited.json')
	.then(res => {
		return ldjsonBody(res.body)
			.on('data', obj => console.log(obj)) // print each received object
			.on('error', err => {
				console.error(err.chunk); // log the failing json chunk
				console.error(err); // log the json parse error
			})
			.on('end', () => {
				// parsing of the complete body is finished
			});
	})
	.then(() => {
		// parsing of the complete body is finished
	})

Requirement

You'll need either native Promise and TextDecoder implementations or polyfills.

API

ldjsonBody(bodyStream, options)

NameTypeDescription
bodyStreamReadableStreamThe response body stream to parse json from
optionsObjectSee Options

Returns: a Promise Emitter, i.e. a Promise enhanced with EventEmitter functions like on and off (for available events see Events).

Options

options.delimiter

Type: String
Default: "\n"

Set delimiter when parsing the response. Each delimiter indicates the start of a new json object.

Events

Event: data

Emitted for each found and parsed json object in the response body.

Event: error

Emitted if an error occurs when parsing a chunk of json. error.chunk is set to the failing string.

Event: end

Emitted when the whole body have been read and parsed.

License

MIT © Joakim Carlstein and eBay Inc