request/lib/json_parser.js

34 lines
690 B
JavaScript
Raw Normal View History

2023-10-25 18:45:16 +08:00
export class JSONParser {
data = Buffer.from('')
bytesWritten = 0
2020-09-16 20:07:28 +08:00
2023-10-25 18:45:16 +08:00
initWithLength(length) {
this.data = Buffer.alloc(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) {
if (this.data.length >= this.bytesWritten + buffer.length) {
buffer.copy(this.data, this.bytesWritten)
} else {
this.data = Buffer.concat([this.data, buffer])
}
this.bytesWritten += buffer.length
return buffer.length
}
2023-10-26 19:02:46 +08:00
2023-10-25 18:45:16 +08:00
end() {
var data = this.data.toString('utf8')
var fields
try {
fields = JSON.parse(data)
} catch (e) {
fields = Function(`try{return ${data}}catch(e){}`)() || data
}
2023-10-26 19:02:46 +08:00
2023-10-25 18:45:16 +08:00
this.onField(false, fields)
this.data = null
2023-10-26 19:02:46 +08:00
2023-10-25 18:45:16 +08:00
this.onEnd()
2020-09-16 20:07:28 +08:00
}
}