request/lib/octet_parser.js

87 lines
1.6 KiB
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 BufferParser extends EventEmitter {
#buf = Buffer.from('')
#byteLen = 0
initLength(length) {
this.#byteLen = length
}
write(buffer) {
this.#buf = Buffer.concat([this.#buf, buffer])
}
end() {
if (this.#buf.length === this.#byteLen) {
this.emit('buffer', this.#buf)
this.emit('end')
this.#buf = null
} else {
this.emit(
'error',
new Error(
`The uploaded data is incomplete. Expected ${
this.#byteLen
}, Received ${this.#buf.length} .`
)
)
}
}
}
export class EmptyParser extends EventEmitter {
write() {}
end() {
this.emit('end')
}
}
对Http的request进一步封装, 提供常用的API
JavaScript 100%