request/lib/json_parser.js

37 lines
863 B
JavaScript
Raw Normal View History

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) {
try{
// 非标准的json语法,尝试用 Function 解析
fields = Function(`try{return ${data}}catch(e){}`)()
}catch(err){}
}
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 {
this.emit('error', new Error(`The uploaded data is incomplete. Expected ${this.#byteLen}, Received ${this.#buff.length} .`))
}
2020-09-16 20:07:28 +08:00
}
}