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

Assembler receives a token stream and assembles JavaScript objects. It is used as a building block for streamers.

Introduction

const Asm = require('stream-json/Assembler');
const {parser} = require('stream-json');
const {chain}  = require('stream-chain');

const fs   = require('fs');
const zlib = require('zlib');

const pipeline = chain([
  fs.createReadStream('data.json.gz'),
  zlib.createGunzip(),
  parser()
]);

const asm = Asm.connectTo(pipeline);
asm.on('done', asm => console.log(asm.current));

API

Assembler is based on EventEmitter. Its constructor takes no arguments.

Public properties

current

The current object being assembled. If it is an array, new subobjects will be added to it. If it is an object, new properties will be added to it. Otherwise, it can be one of this: a string, a number, null, true, false.

key

A string for a property key, or null, if unused. This variable is used to keep a property name until a corresponding subobject is assembled.

stack

An array of parent objects for an object in current. This array is used as a stack. Even values correspond to parent objects, while odd values contain a property key or null.

Essentially, when a new object comes in the current values of current and key are pushed on stack and reinitialized. When current is fully assembled, it is placed in its parent object possibly using key, and old values of current and key are restored from stack.

done

It is a boolean flag. It indicates that a current object is fully assembled. When this flag flips to true an event called done is issued as well.

In case of a stream of multiple JSON objects, done can be flipped to true multiple times.

get depth()

A getter, which returns a current object depth.

Clone this wiki locally