Skip to content
Eugene Lazutkin edited this page Jun 18, 2018 · 2 revisions

withParser() is a helper, which creates a stream instance using a factory function, a Parser instance, and pipes its output into the created stream.

This utility is exposed as a static method on most streams provided by stream-json.

Introduction

const withParser = require('stream-json/utils/withParser'); const {pick} = require('stream-json/filters/Pick'); const fs = stream('fs'); const pipeline = fs.createReadStream('sample.json') .pipe(withParser(pick, {filter: 'data'})); pipeline.on('data', data => console.log(data));

API

withParser() takes two arguments:

  • fn is a factory function, which takes an options object and returns a stream in object mode.
  • options is an object described in Parser's options. It is used to initialize both streams (a Parser instance and a stream returned by fn()).

It returns a stream produced by stream-chain, which wraps the pipeline. The most important utility of withParser() is that it correctly sets object modes of the returned stream: object mode for the Readable part and text mode for the Writable part.

The whole implementation of withParser() is very simple:

const Chain = require('stream-chain'); const Parser = require('../Parser'); const withParser = (fn, options) => new Chain([new Parser(options), fn(options)], Object.assign({}, options, {writableObjectMode: false, readableObjectMode: true}));
Clone this wiki locally