Skip to content
Eugene Lazutkin edited this page Mar 16, 2026 · 5 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/with-parser.js');
const {pick} = require('stream-json/filters/pick.js');
const fs = require('fs');

const pipeline = fs.createReadStream('sample.json').pipe(withParser.asStream(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 — combined Parser and component options. Passed to both the parser and fn().

Returns a flushable function (or a Duplex stream via withParser.asStream()) wrapping a parser() + fn() pipeline via stream-chain. The stream variant sets text-mode writable and object-mode readable.

The implementation:

const {asStream: makeStream, gen} = require('stream-chain');
const parser = require('../parser.js');

const withParser = (fn, options) => gen(parser(options), fn(options));
const asStream = (fn, options) => makeStream(withParser(fn, options), {writableObjectMode: false, readableObjectMode: true});

withParser() returns a generator function for use in chain(). withParser.asStream() wraps it as a Duplex stream.

Clone this wiki locally