request/lib/json_parser.js

44 lines
928 B
JavaScript
Raw Permalink 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 {
2024-07-10 16:44:17 +08:00
#buf = Buffer.from('')
2023-10-27 19:16:32 +08:00
#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) {
2024-07-10 16:44:17 +08:00
this.#buf = Buffer.concat([this.#buf, 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() {
2024-07-10 16:44:17 +08:00
if (this.#buf.length === this.#byteLen) {
let data = this.#buf.toString()
2023-10-27 19:16:32 +08:00
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
2024-07-10 16:44:17 +08:00
this.#buf = null
2023-10-27 19:16:32 +08:00
} else {
2023-10-30 16:41:37 +08:00
this.emit(
'error',
new Error(
`The uploaded data is incomplete. Expected ${
this.#byteLen
2024-07-10 16:44:17 +08:00
}, Received ${this.#buf.length} .`
2023-10-30 16:41:37 +08:00
)
)
2023-10-27 19:16:32 +08:00
}
2020-09-16 20:07:28 +08:00
}
}