-
- Notifications
You must be signed in to change notification settings - Fork 51
withParser()
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.
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));withParser() takes two arguments:
-
fnis a factory function, which takes an options object and returns a stream in object mode. -
optionsis an object described in Parser's options. It is used to initialize both streams (aParserinstance and a stream returned byfn()).
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}));