request/lib/octet_parser.js

87 lines
1.6 KiB
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
}
2024-07-10 16:44:17 +08:00
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} .`
)
)
}
}
}
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
}