request/lib/octet_parser.js

57 lines
1009 B
JavaScript
Raw Normal View History

2023-10-27 19:16:32 +08:00
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/10/27 14:23:22
*/
import { EventEmitter } from 'node:events'
import File from './file.js'
2020-09-16 20:07:28 +08:00
2023-10-25 18:45:16 +08:00
export class OctetParser extends EventEmitter {
2023-10-27 19:16:32 +08:00
#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
}
2023-10-26 19:02:46 +08:00
write(buffer) {
2023-10-27 19:16:32 +08:00
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} .`
)
)
}
})
2023-10-26 19:02:46 +08:00
}
2023-10-27 19:16:32 +08:00
}
export class EmptyParser extends EventEmitter {
write() {}
2023-10-26 19:02:46 +08:00
end() {
this.emit('end')
}
2020-09-16 20:07:28 +08:00
}