精简代码

v2
yutent 2023-10-30 16:59:54 +08:00
parent 30f0ca48e3
commit e7146ce5ef
2 changed files with 15 additions and 44 deletions

View File

@ -2,8 +2,6 @@ import crypto from 'node:crypto'
import fs from 'node:fs'
import { join } from 'node:path'
import { EventEmitter } from 'node:events'
import { Stream } from 'node:stream'
import { StringDecoder } from 'node:string_decoder'
import File from './file.js'
import { MultipartParser } from './multipart_parser.js'
@ -57,8 +55,9 @@ export default class IncomingForm extends EventEmitter {
this.uploadDir = opts.uploadDir
this.encoding = opts.encoding || 'utf-8'
// Parse headers and setup the parser, ready to start listening for data.
this.writeHeaders(req.headers)
this.headers = req.headers
this.#parseContentLength()
this.#parseContentType()
req
.on('error', err => {
@ -69,7 +68,7 @@ export default class IncomingForm extends EventEmitter {
this.emit('aborted')
this.#clearUploads()
})
.on('data', buffer => this.write(buffer))
.on('data', buffer => this.#write(buffer))
.on('end', () => {
if (this.#error) {
return
@ -81,13 +80,7 @@ export default class IncomingForm extends EventEmitter {
})
}
writeHeaders(headers) {
this.headers = headers
this.#parseContentLength()
this.#parseContentType()
}
write(buffer) {
#write(buffer) {
if (this.#error) {
return
}
@ -100,42 +93,16 @@ export default class IncomingForm extends EventEmitter {
this.#parser.write(buffer)
}
pause() {
try {
this.#req.pause()
} catch (err) {
if (!this.#ended) {
this.#handleError(err)
}
return false
}
return true
}
resume() {
try {
this.#req.resume()
} catch (err) {
if (!this.#ended) {
this.#handleError(err)
}
return false
}
return true
}
#handlePart(part) {
if (part.filename === undefined) {
let value = ''
let decoder = new StringDecoder(this.encoding)
let value = Buffer.from('')
part
.on('data', buffer => {
value += decoder.write(buffer)
.on('data', buff => {
value = Buffer.concat([value, buff])
})
.on('end', () => {
this.emit('field', part.name, value)
this.emit('field', part.name, value.toString(this.encoding))
})
} else {
let file = new File({
@ -218,7 +185,7 @@ export default class IncomingForm extends EventEmitter {
this.#parser = new MultipartParser(boundary)
this.#parser.$partBegin = function () {
part = new Stream()
part = new EventEmitter()
part.readable = true
part.headers = {}
part.name = null

View File

@ -1,4 +1,8 @@
import { EventEmitter } from 'node:events'
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/10/30 16:41:59
*/
let s = 0
const STATE_DICT = {