Skip to content

joakimbeng/ldjson-body

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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)

Name Type Description
bodyStream ReadableStream The response body stream to parse json from
options Object See 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

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published