Skip to content
Eugene Lazutkin edited this page Jun 18, 2018 · 1 revision

emit() helps to deal with different types of data items produced by Parser and filters. It takes a stream instance, adds a data listener, then emits events on the same stream instance, which correspond to data types: startObject, endNumber, nullValue, and so on.

Introduction

const {parser} = require('stream-json/Parser');
const emit = require('stream-json/utils/emit');
const fs = require('fs');

const pipeline = fs.createReadStream('sample.json').pipe(parser());
emit(pipeline);

let objectCounter = 0;
pipeline.on('startObject', () => ++objectCounter);
pipeline.on('end', console.log(`Found ${objectCounter} objects.`));

API

emit() is a function with one argument, which should be a stream. Usually, it is the last stream of the pipeline: a parser, or a filter. Its returned value is the same stream for possible chaining.

The whole implementation of emit() is very simple:

const emit = stream => {
  stream.on('data', item => stream.emit(item.name, item.value));
  return stream;
};
Clone this wiki locally