import { EventEmitter } from 'node:events' export class JSONParser extends EventEmitter { #buff = Buffer.from('') #byteLen = 0 initLength(length) { this.#byteLen = length } write(buffer) { this.#buff = Buffer.concat([this.#buff, buffer]) } end() { if (this.#buff.length === this.#byteLen) { let data = this.#buff.toString() let fields = data try { fields = JSON.parse(data) } catch (e) { try { // 非标准的json语法,尝试用 Function 解析 fields = Function(`try{return ${data}}catch(e){}`)() } catch (err) {} } this.emit('field', false, fields) this.emit('end') this.#buff = null } else { this.emit( 'error', new Error( `The uploaded data is incomplete. Expected ${ this.#byteLen }, Received ${this.#buff.length} .` ) ) } } }