-
-
Notifications
You must be signed in to change notification settings - Fork 53
withParser()
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/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));withParser() takes two arguments:
-
fnis 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 andfn().
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. withParser.asWebStream() wraps it as a Web {readable, writable} pair.
withParser ships in two substrate-specific entries:
-
Node —
stream-json/utils/with-parser.js. HasasStreamandasWebStream. -
Web —
stream-json/web/utils/with-parser.js. HasasWebStreamonly. Pulls in no Node-stream imports.
// Web
import withParser from 'stream-json/web/utils/with-parser.js';
import {pick} from 'stream-json/web/filters/pick.js';
const {readable, writable} = withParser.asWebStream(pick, {filter: 'data'});
sourceReadable.pipeTo(writable);
for await (const tok of readable) console.log(tok);Most components also expose withParser, withParserAsStream, and withParserAsWebStream directly on the factory — see the per-component pages for shortcuts.
Start here
Core
Filters
Streamers
Essentials
Utilities
File I/O (Node-only)
JSONC
JSONL (use stream-chain)
Reference
Built on stream-chain