2023-10-27 19:16:32 +08:00
|
|
|
import { EventEmitter } from 'node:events'
|
2020-09-16 20:07:28 +08:00
|
|
|
|
2023-10-27 19:16:32 +08:00
|
|
|
export class JSONParser extends EventEmitter {
|
|
|
|
#buff = Buffer.from('')
|
|
|
|
#byteLen = 0
|
|
|
|
|
|
|
|
initLength(length) {
|
|
|
|
this.#byteLen = length
|
2020-09-16 20:07:28 +08:00
|
|
|
}
|
2023-10-26 19:02:46 +08:00
|
|
|
|
2023-10-25 18:45:16 +08:00
|
|
|
write(buffer) {
|
2023-10-27 19:16:32 +08:00
|
|
|
this.#buff = Buffer.concat([this.#buff, buffer])
|
2023-10-25 18:45:16 +08:00
|
|
|
}
|
2023-10-26 19:02:46 +08:00
|
|
|
|
2023-10-25 18:45:16 +08:00
|
|
|
end() {
|
2023-10-27 19:16:32 +08:00
|
|
|
if (this.#buff.length === this.#byteLen) {
|
|
|
|
let data = this.#buff.toString()
|
|
|
|
let fields = data
|
|
|
|
try {
|
|
|
|
fields = JSON.parse(data)
|
|
|
|
} catch (e) {
|
2023-10-30 16:41:37 +08:00
|
|
|
try {
|
2023-10-27 19:16:32 +08:00
|
|
|
// 非标准的json语法,尝试用 Function 解析
|
|
|
|
fields = Function(`try{return ${data}}catch(e){}`)()
|
2023-10-30 16:41:37 +08:00
|
|
|
} catch (err) {}
|
2023-10-27 19:16:32 +08:00
|
|
|
}
|
2023-10-26 19:02:46 +08:00
|
|
|
|
2023-10-27 19:16:32 +08:00
|
|
|
this.emit('field', false, fields)
|
|
|
|
this.emit('end')
|
2023-10-26 19:02:46 +08:00
|
|
|
|
2023-10-27 19:16:32 +08:00
|
|
|
this.#buff = null
|
|
|
|
} else {
|
2023-10-30 16:41:37 +08:00
|
|
|
this.emit(
|
|
|
|
'error',
|
|
|
|
new Error(
|
|
|
|
`The uploaded data is incomplete. Expected ${
|
|
|
|
this.#byteLen
|
|
|
|
}, Received ${this.#buff.length} .`
|
|
|
|
)
|
|
|
|
)
|
2023-10-27 19:16:32 +08:00
|
|
|
}
|
2020-09-16 20:07:28 +08:00
|
|
|
}
|
|
|
|
}
|