request/lib/octet_parser.js

57 lines
1009 B
JavaScript

/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/10/27 14:23:22
*/
import { EventEmitter } from 'node:events'
import File from './file.js'
export class OctetParser extends EventEmitter {
#file = null
#byteLen = 0
#wroteLen = 0
constructor(name, type, path) {
super()
this.#file = new File({ path, name, type })
this.#file.open()
}
initLength(length) {
this.#byteLen = length
}
write(buffer) {
this.#file.write(buffer)
this.#wroteLen += buffer.length
}
end() {
this.#file.end(_ => {
if (this.#wroteLen === this.#byteLen) {
this.emit('file', this.#file)
this.emit('end')
} else {
this.emit(
'error',
new Error(
`The uploaded data is incomplete. Expected ${
this.#byteLen
}, Received ${this.#wroteLen} .`
)
)
}
})
}
}
export class EmptyParser extends EventEmitter {
write() {}
end() {
this.emit('end')
}
}
对Http的request进一步封装, 提供常用的API
JavaScript 100%