import { EventEmitter } from 'node:events' export class JSONParser extends EventEmitter { #buf = Buffer.from('') #byteLen = 0 initLength(length) { this.#byteLen = length } write(buffer) { this.#buf = Buffer.concat([this.#buf, buffer]) } end() { if (this.#buf.length === this.#byteLen) { let data = this.#buf.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.#buf = null } else { this.emit( 'error', new Error( `The uploaded data is incomplete. Expected ${ this.#byteLen }, Received ${this.#buf.length} .` ) ) } } }