UNPKG

@yukiakai/json-stream-parser

Version:

Streaming JSON parser that handles fragmented data and emits full JSON objects when complete.

2 lines (1 loc) 936 B
import{EventEmitter as a}from"events";var s=class extends a{constructor(){super(...arguments);this.buffer="";this.depthCurly=0;this.depthSquare=0;this.inString=!1;this.escape=!1}write(n){let r=n.toString();for(let e=0;e<r.length;e++){let t=r[e];if(this.buffer+=t,this.inString){t==='"'&&!this.buffer.endsWith('\\"')&&(this.inString=!1);continue}if(t==='"'){this.inString=!0;continue}if(t==="{"?this.depthCurly++:t==="}"?this.depthCurly--:t==="["?this.depthSquare++:t==="]"&&this.depthSquare--,this.depthCurly<0||this.depthSquare<0){this.emit("error",new Error("Unexpected closing bracket or brace")),this.reset();return}if(this.depthCurly===0&&this.depthSquare===0&&!this.inString){try{let i=JSON.parse(this.buffer);this.emit("data",i)}catch(i){this.emit("error",new Error(`Invalid JSON: ${i}`))}this.reset()}}}reset(){this.buffer="",this.depthCurly=0,this.depthSquare=0,this.inString=!1,this.escape=!1}};export{s as JsonStreamParser};