request/lib/urlencoded_parser.js

44 lines
850 B
JavaScript
Raw Normal View History

2023-10-27 19:16:32 +08:00
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/10/27 12:14:05
*/
import { EventEmitter } from 'node:events'
2024-07-16 17:45:52 +08:00
import { querystring } from './helper.js'
2023-10-27 19:16:32 +08:00
export class UrlencodedParser extends EventEmitter {
2024-07-10 16:44:17 +08:00
#buf = Buffer.from('')
2024-07-16 17:45:52 +08:00
#byteLen = 0
initLength(length) {
this.#byteLen = length
}
2023-10-27 19:16:32 +08:00
write(buffer) {
2024-07-10 16:44:17 +08:00
this.#buf = Buffer.concat([this.#buf, buffer])
2023-10-27 19:16:32 +08:00
}
end() {
2024-07-16 17:45:52 +08:00
if (this.#buf.length === this.#byteLen) {
let data = this.#buf.toString()
let fields = querystring(data)
2023-10-30 16:41:37 +08:00
2024-07-16 17:45:52 +08:00
this.#buf = null
2023-10-30 16:41:37 +08:00
2024-07-16 17:45:52 +08:00
this.emit('field', 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} .`
)
)
}
2023-10-27 19:16:32 +08:00
}
}