Compare commits

...

6 Commits

Author SHA1 Message Date
yutent 2ab38350a8 2.0 2023-10-30 17:04:07 +08:00
yutent e7146ce5ef 精简代码 2023-10-30 16:59:54 +08:00
yutent 30f0ca48e3 完成2.0版重构 2023-10-30 16:41:37 +08:00
yutent 5e827928ba 一大波重构 2023-10-27 19:16:32 +08:00
yutent 94a997bb8a 一大波更新 2023-10-26 19:02:46 +08:00
yutent 6b3a44d387 调整语法, 兼容bun 2023-10-25 18:45:16 +08:00
11 changed files with 924 additions and 1141 deletions

1
.gitignore vendored
View File

@ -9,4 +9,5 @@
.vscode .vscode
.tmp/
node_modules/ node_modules/

320
index.js
View File

@ -8,17 +8,17 @@ import 'es.shim'
import Parser from './lib/index.js' import Parser from './lib/index.js'
import { parseCookie } from './lib/cookie.js' import { parseCookie } from './lib/cookie.js'
import fs from 'iofs' import fs from 'iofs'
import URL from 'url' import { fileURLToPath, parse } from 'node:url'
import QS from 'querystring' import QS from 'node:querystring'
import PATH from 'path' import { dirname, resolve } from 'node:path'
const DEFAULT_FORM_TYPE = 'application/x-www-form-urlencoded' const DEFAULT_FORM_TYPE = 'application/x-www-form-urlencoded'
var __dirname = PATH.dirname(URL.fileURLToPath(import.meta.url)) const __dirname = dirname(fileURLToPath(import.meta.url))
var tmpdir = PATH.resolve(__dirname, '.tmp/') const tmpdir = resolve(__dirname, '.tmp/')
var encode = encodeURIComponent const encode = encodeURIComponent
var decode = decodeURIComponent const decode = decodeURIComponent
if (fs.isdir(tmpdir)) { if (fs.isdir(tmpdir)) {
fs.rm(tmpdir, true) fs.rm(tmpdir, true)
@ -36,34 +36,50 @@ function hideProperty(host, name, value) {
} }
export default class Request { export default class Request {
constructor(req, res) { #req = null
#res = null
#opts = {}
#query = null
#body = null
#cookies = Object.create(null)
method = 'GET'
path = []
url = ''
host = '127.0.0.1'
constructor(req, res, opts = {}) {
this.method = req.method.toUpperCase() this.method = req.method.toUpperCase()
this.params = {}
hideProperty(this, 'origin', { req, res }) this.#req = req
hideProperty(this, '__GET__', null) this.#res = res
hideProperty(this, '__POST__', null)
hideProperty(this, '__COOKIE__', parseCookie(this.header('cookie') || ''))
this.__fixUrl() this.host = req.headers['host']
this.#cookies = parseCookie(this.headers['cookie'] || '')
Object.assign(this.#opts, opts)
this.#init()
} }
// 修正请求的url // 修正请求的url
__fixUrl() { #init() {
let _url = URL.parse(this.origin.req.url) let _url = parse(this.#req.url)
.pathname.slice(1) .pathname.slice(1)
.replace(/[\/]+$/, '') .replace(/[\/]+$/, '')
let app = '' // 将作为主控制器(即apps目录下的应用) let app = '' // 将作为主控制器(即apps目录下的应用)
let pathArr = [] let pathArr = []
let tmpArr = []
// URL上不允许有非法字符 // URL上不允许有非法字符
if (/[^\w-/.@~!$&:+'=]/.test(decode(_url))) { if (/[^\w-/.,@~!$&:+'"=]/.test(decode(_url))) {
this.origin.res.rendered = true this.#res.rendered = true
this.origin.res.writeHead(400, { this.#res.writeHead(400, {
'X-debug': `url [/${encode(_url)}] contains invalid characters` 'X-debug': `url [/${encode(_url)}] contains invalid characters`
}) })
return this.origin.res.end(`Invalid characters: /${_url}`) return this.#res.end(`Invalid characters: /${_url}`)
} }
// 修正url中可能出现的"多斜杠" // 修正url中可能出现的"多斜杠"
@ -86,200 +102,156 @@ export default class Request {
pathArr.shift() pathArr.shift()
// 将path第3段之后的部分, 每2个一组转为key-val数据对象, 存入params中
tmpArr = pathArr.slice(1).concat()
while (tmpArr.length) {
this.params[tmpArr.shift()] = tmpArr.shift() || null
}
tmpArr = undefined
for (let i in this.params) {
if (!this.params[i]) {
continue
}
// 修正数字类型,把符合条件的数字字符串转为数字(也许会误转, 但总的来说是利大弊)
this.params[i] = Number.parse(this.params[i])
}
this.app = app this.app = app
this.url = _url this.url = _url
this.path = pathArr this.path = pathArr
} }
/** /**
* [get 同php的$_GET] * [解析请求体, 需要 await ]
*/
get(key = '', xss = true) {
xss = !!xss
if (!this.__GET__) {
let para = URL.parse(this.origin.req.url).query
para = Object.assign({}, QS.parse(para))
if (xss) {
for (let i in para) {
if (!para[i]) {
continue
}
if (Array.isArray(para[i])) {
para[i] = para[i].map(it => {
it = Number.parse(it.trim().xss())
return it
})
} else {
para[i] = Number.parse(para[i].trim().xss())
}
}
}
this.__GET__ = para
}
return key
? this.__GET__.hasOwnProperty(key)
? this.__GET__[key]
: null
: this.__GET__
}
/**
* [post 接收post, 需要 await ]
* @param {Str} key [字段] * @param {Str} key [字段]
*/ */
post(key = '', xss = true) { #parseBody() {
let para = {}
let out = Promise.defer() let out = Promise.defer()
let form, contentType let form, contentType
xss = !!xss this.#body = {}
//如果之前已经缓存过,则直接从缓存读取
if (this.__POST__) {
if (key) {
return this.__POST__.hasOwnProperty(key) ? this.__POST__[key] : null
} else {
return this.__POST__
}
}
contentType = this.header('content-type') || DEFAULT_FORM_TYPE contentType = this.header('content-type') || DEFAULT_FORM_TYPE
form = new Parser() form = new Parser(this.#req, { ...this.#opts, uploadDir: tmpdir })
form.uploadDir = tmpdir
form.parse(this.origin.req)
form.on('field', (name, value) => { form
if (name === false) { .on('field', (name, value) => {
para = value if (name === false) {
return this.#body = value
} return
if (~contentType.indexOf('urlencoded')) {
if (
name.slice(0, 2) === '{"' &&
(name.slice(-2) === '"}' || value.slice(-2) === '"}')
) {
name = name.replace(/\s/g, '+')
if (value.slice(0, 1) === '=') value = '=' + value
return Object.assign(para, JSON.parse(name + value))
} }
} if (~contentType.indexOf('urlencoded')) {
if (
name.slice(0, 2) === '{"' &&
(name.slice(-2) === '"}' || value.slice(-2) === '"}')
) {
name = name.replace(/\s/g, '+')
if (typeof value === 'string') { if (value.slice(0, 1) === '=') value = '=' + value
value = xss ? value.xss() : value
}
if (name.slice(-2) === '[]') { return Object.assign(this.#body, JSON.parse(name + value))
name = name.slice(0, -2) }
if (typeof value === 'string') {
value = [value]
} }
} else if (name.slice(-1) === ']') {
let key = name.slice(name.lastIndexOf('[') + 1, -1)
name = name.slice(0, name.lastIndexOf('['))
//多解析一层对象(也仅支持到这一层) if (name.slice(-2) === '[]') {
if (name.slice(-1) === ']') { name = name.slice(0, -2)
let pkey = name.slice(name.lastIndexOf('[') + 1, -1) if (typeof value === 'string') {
value = [value]
}
} else if (name.slice(-1) === ']') {
let key = name.slice(name.lastIndexOf('[') + 1, -1)
name = name.slice(0, name.lastIndexOf('[')) name = name.slice(0, name.lastIndexOf('['))
if (!para.hasOwnProperty(name)) { //多解析一层对象(也仅支持到这一层)
para[name] = {} if (name.slice(-1) === ']') {
} let pkey = name.slice(name.lastIndexOf('[') + 1, -1)
name = name.slice(0, name.lastIndexOf('['))
if (!para[name].hasOwnProperty(pkey)) { if (!this.#body.hasOwnProperty(name)) {
para[name][pkey] = {} this.#body[name] = {}
}
para[name][pkey][key] = value
} else {
if (!para.hasOwnProperty(name)) {
para[name] = {}
}
para[name][key] = value
}
return
}
para[name] = value
})
form.on('file', (name, file) => {
if (name.slice(-2) === '[]') {
name = name.slice(0, -2)
}
if (!para.hasOwnProperty(name)) {
para[name] = file
} else {
if (!Array.isArray(para[name])) {
para[name] = [para[name]]
}
para[name].push(file)
}
})
form.on('error', out.reject)
form.on('end', err => {
if (~contentType.indexOf('urlencoded')) {
for (let i in para) {
if (typeof para[i] === 'string') {
if (!para[i]) {
continue
} }
para[i] = Number.parse(para[i])
if (!this.#body[name].hasOwnProperty(pkey)) {
this.#body[name][pkey] = {}
}
this.#body[name][pkey][key] = value
} else {
if (!this.#body.hasOwnProperty(name)) {
this.#body[name] = {}
}
this.#body[name][key] = value
}
return
}
this.#body[name] = value
})
.on('file', (name, file) => {
if (name === false) {
this.#body = file
} else {
if (name.slice(-2) === '[]') {
name = name.slice(0, -2)
}
if (!this.#body.hasOwnProperty(name)) {
this.#body[name] = file
} else {
if (!Array.isArray(this.#body[name])) {
this.#body[name] = [this.#body[name]]
}
this.#body[name].push(file)
} }
} }
} })
this._postParam = para .on('error', out.reject)
if (key) { .on('end', _ => {
return out.resolve(para.hasOwnProperty(key) ? para[key] : null) if (contentType.includes('urlencoded')) {
} else { for (let i in this.#body) {
return out.resolve(para) if (typeof this.#body[i] === 'string') {
} if (!this.#body[i]) {
}) continue
}
this.#body[i] = Number.parse(this.#body[i])
}
}
}
out.resolve(this.#body)
})
return out.promise return out.promise
} }
//获取响应头 //获取响应头
header(key = '') { header(key = '') {
key = key ? (key + '').toLowerCase() : null key = key ? (key + '').toLowerCase() : null
return !!key ? this.origin.req.headers[key] : this.origin.req.headers return !!key ? this.#req.headers[key] : this.#req.headers
} }
// 读取cookie // 读取cookie
cookie(key) { cookie(key) {
if (key) { if (key) {
return this.__COOKIE__[key] return this.#cookies[key]
} }
return this.__COOKIE__ return this.#cookies
}
get query() {
if (!this.#query) {
let para = parse(this.#req.url).query
this.#query = QS.parse(para)
}
return this.#query
}
get body() {
if (this.#body) {
return this.#body
}
return this.#parseBody()
}
get cookies() {
return this.#cookies
}
get headers() {
return this.#req.headers
} }
//获取客户端IP //获取客户端IP
ip() { get ip() {
return ( return (
this.header('x-real-ip') || this.headers['x-real-ip'] ||
this.header('x-forwarded-for') || this.headers['x-forwarded-for'] ||
this.origin.req.connection.remoteAddress.replace('::ffff:', '') this.#req.connection.remoteAddress.replace('::ffff:', '')
) )
} }
} }

View File

@ -4,16 +4,16 @@
*/ */
// var KEY_REGEXP = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/ // var KEY_REGEXP = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/
var SPLIT_REGEXP = /; */ const SPLIT_REGEXP = /; */
// var encode = encodeURIComponent // var encode = encodeURIComponent
var decode = decodeURIComponent const decode = decodeURIComponent
/** /**
* [parse 格式化字符串] * [parse 格式化字符串]
*/ */
export function parseCookie(str) { export function parseCookie(str) {
var obj = {} let obj = {}
var pairs let pairs
if (typeof str !== 'string') { if (typeof str !== 'string') {
return {} return {}
@ -27,8 +27,8 @@ export function parseCookie(str) {
continue continue
} }
var key = item[0].trim() let key = item[0].trim()
var val = item[1].trim() let val = item[1].trim()
obj[key] = decode(val) obj[key] = decode(val)
} }

View File

@ -1,70 +1,48 @@
import util from 'util' import { WriteStream } from 'node:fs'
import { WriteStream } from 'fs' import { EventEmitter } from 'node:events'
import { EventEmitter } from 'events'
import crypto from 'crypto'
export default function File(properties) { export default class File extends EventEmitter {
EventEmitter.call(this) #stream = null
this.size = 0 size = 0
this.path = null path = null
this.name = null name = null
this.type = null type = null
this.hash = null lastModifiedDate = null
this.lastModifiedDate = null
this._writeStream = null constructor(props = {}) {
super()
for (var key in properties) { for (let key in props) {
this[key] = properties[key] this[key] = props[key]
}
} }
if (typeof this.hash === 'string') { open() {
this.hash = crypto.createHash(properties.hash) this.#stream = new WriteStream(this.path)
} else { }
this.hash = null
toJSON() {
return {
size: this.size,
path: this.path,
name: this.name,
type: this.type,
mtime: this.lastModifiedDate,
length: this.length,
filename: this.name,
mime: this.type
}
}
write(buffer) {
this.#stream.write(buffer, _ => {
this.size += buffer.length
})
}
end(callback) {
this.lastModifiedDate = new Date()
this.#stream.end(callback)
} }
} }
util.inherits(File, EventEmitter)
File.prototype.open = function() {
this._writeStream = new WriteStream(this.path)
}
File.prototype.toJSON = function() {
return {
size: this.size,
path: this.path,
name: this.name,
type: this.type,
mtime: this.lastModifiedDate,
length: this.length,
filename: this.filename,
mime: this.mime
}
}
File.prototype.write = function(buffer, cb) {
var self = this
if (self.hash) {
self.hash.update(buffer)
}
this._writeStream.write(buffer, function() {
self.lastModifiedDate = new Date()
self.size += buffer.length
self.emit('progress', self.size)
cb()
})
}
File.prototype.end = function(cb) {
var self = this
if (self.hash) {
self.hash = self.hash.digest('hex')
}
this._writeStream.end(function() {
self.emit('end')
cb()
})
}

View File

@ -1,571 +1,346 @@
import crypto from 'crypto' import crypto from 'node:crypto'
import fs from 'fs' import fs from 'node:fs'
import util from 'util' import { join } from 'node:path'
import path from 'path' import { EventEmitter } from 'node:events'
import File from './file.js'
import { EventEmitter } from 'events'
import { Stream } from 'stream'
import { StringDecoder } from 'string_decoder'
import File from './file.js'
import { MultipartParser } from './multipart_parser.js' import { MultipartParser } from './multipart_parser.js'
import { QuerystringParser } from './querystring_parser.js' import { UrlencodedParser } from './urlencoded_parser.js'
import { OctetParser } from './octet_parser.js' import { OctetParser, EmptyParser } from './octet_parser.js'
import { JSONParser } from './json_parser.js' import { JSONParser } from './json_parser.js'
export default function IncomingForm(opts) { function randomPath(uploadDir) {
EventEmitter.call(this) var name = 'upload_' + crypto.randomBytes(16).toString('hex')
return join(uploadDir, name)
opts = opts || {}
this.error = null
this.ended = false
this.maxFields = opts.maxFields || 1000
this.maxFieldsSize = opts.maxFieldsSize || 2 * 1024 * 1024
this.keepExtensions = opts.keepExtensions || false
this.uploadDir = opts.uploadDir
this.encoding = opts.encoding || 'utf-8'
this.headers = null
this.type = null
this.hash = opts.hash || false
this.multiples = opts.multiples || false
this.bytesReceived = null
this.bytesExpected = null
this._parser = null
this._flushing = 0
this._fieldsSize = 0
this.openedFiles = []
} }
util.inherits(IncomingForm, EventEmitter) function parseFilename(headerValue) {
let matches = headerValue.match(/\bfilename="(.*?)"($|; )/i)
IncomingForm.prototype.parse = function(req, cb) { if (!matches) {
this.pause = function() {
try {
req.pause()
} catch (err) {
// the stream was destroyed
if (!this.ended) {
// before it was completed, crash & burn
this._error(err)
}
return false
}
return true
}
this.resume = function() {
try {
req.resume()
} catch (err) {
// the stream was destroyed
if (!this.ended) {
// before it was completed, crash & burn
this._error(err)
}
return false
}
return true
}
// Setup callback first, so we don't miss anything from data events emitted
// immediately.
if (cb) {
var fields = {},
files = {}
this.on('field', function(name, value) {
fields[name] = value
})
.on('file', function(name, file) {
if (this.multiples) {
if (files[name]) {
if (!Array.isArray(files[name])) {
files[name] = [files[name]]
}
files[name].push(file)
} else {
files[name] = file
}
} else {
files[name] = file
}
})
.on('error', function(err) {
cb(err, fields, files)
})
.on('end', function() {
cb(null, fields, files)
})
}
// Parse headers and setup the parser, ready to start listening for data.
this.writeHeaders(req.headers)
// Start listening for data.
var self = this
req
.on('error', function(err) {
self._error(err)
})
.on('aborted', function() {
self.emit('aborted')
self._error(new Error('Request aborted'))
})
.on('data', function(buffer) {
self.write(buffer)
})
.on('end', function() {
if (self.error) {
return
}
var err = self._parser.end()
if (err) {
self._error(err)
}
})
return this
}
IncomingForm.prototype.writeHeaders = function(headers) {
this.headers = headers
this._parseContentLength()
this._parseContentType()
}
IncomingForm.prototype.write = function(buffer) {
if (this.error) {
return
}
if (!this._parser) {
this._error(new Error('uninitialized parser'))
return return
} }
this.bytesReceived += buffer.length let filename = matches[1].slice(matches[1].lastIndexOf('\\') + 1)
this.emit('progress', this.bytesReceived, this.bytesExpected)
var bytesParsed = this._parser.write(buffer)
if (bytesParsed !== buffer.length) {
this._error(
new Error(
'parser error, ' +
bytesParsed +
' of ' +
buffer.length +
' bytes parsed'
)
)
}
return bytesParsed
}
IncomingForm.prototype.pause = function() {
// this does nothing, unless overwritten in IncomingForm.parse
return false
}
IncomingForm.prototype.resume = function() {
// this does nothing, unless overwritten in IncomingForm.parse
return false
}
IncomingForm.prototype.onPart = function(part) {
// this method can be overwritten by the user
this.handlePart(part)
}
IncomingForm.prototype.handlePart = function(part) {
var self = this
if (part.filename === undefined) {
var value = '',
decoder = new StringDecoder(this.encoding)
part.on('data', function(buffer) {
self._fieldsSize += buffer.length
if (self._fieldsSize > self.maxFieldsSize) {
self._error(
new Error(
'maxFieldsSize exceeded, received ' +
self._fieldsSize +
' bytes of field data'
)
)
return
}
value += decoder.write(buffer)
})
part.on('end', function() {
self.emit('field', part.name, value)
})
return
}
this._flushing++
var file = new File({
path: this._uploadPath(part.filename),
name: part.filename,
type: part.mime,
hash: self.hash
})
this.emit('fileBegin', part.name, file)
file.open()
this.openedFiles.push(file)
part.on('data', function(buffer) {
if (buffer.length == 0) {
return
}
self.pause()
file.write(buffer, function() {
self.resume()
})
})
part.on('end', function() {
file.end(function() {
self._flushing--
self.emit('file', part.name, file)
self._maybeEnd()
})
})
}
function dummyParser(self) {
return {
end: function() {
self.ended = true
self._maybeEnd()
return null
}
}
}
IncomingForm.prototype._parseContentType = function() {
if (this.bytesExpected === 0) {
this._parser = dummyParser(this)
return
}
if (!this.headers['content-type']) {
this._error(new Error('bad content-type header, no content-type'))
return
}
if (this.headers['content-type'].match(/octet-stream/i)) {
this._initOctetStream()
return
}
if (this.headers['content-type'].match(/urlencoded/i)) {
this._initUrlencoded()
return
}
if (this.headers['content-type'].match(/multipart/i)) {
var m = this.headers['content-type'].match(
/boundary=(?:"([^"]+)"|([^;]+))/i
)
if (m) {
this._initMultipart(m[1] || m[2])
} else {
this._error(new Error('bad content-type header, no multipart boundary'))
}
return
}
if (this.headers['content-type'].match(/json|appliation|plain|text/i)) {
this._initJSONencoded()
return
}
this._error(
new Error(
'bad content-type header, unknown content-type: ' +
this.headers['content-type']
)
)
}
IncomingForm.prototype._error = function(err) {
if (this.error || this.ended) {
return
}
this.error = err
this.emit('error', err)
if (Array.isArray(this.openedFiles)) {
this.openedFiles.forEach(function(file) {
file._writeStream.destroy()
setTimeout(fs.unlink, 0, file.path, function(error) {})
})
}
}
IncomingForm.prototype._parseContentLength = function() {
this.bytesReceived = 0
if (this.headers['content-length']) {
this.bytesExpected = parseInt(this.headers['content-length'], 10)
} else if (this.headers['transfer-encoding'] === undefined) {
this.bytesExpected = 0
}
if (this.bytesExpected !== null) {
this.emit('progress', this.bytesReceived, this.bytesExpected)
}
}
IncomingForm.prototype._newParser = function() {
return new MultipartParser()
}
IncomingForm.prototype._initMultipart = function(boundary) {
this.type = 'multipart'
var parser = new MultipartParser(),
self = this,
headerField,
headerValue,
part
parser.initWithBoundary(boundary)
parser.onPartBegin = function() {
part = new Stream()
part.readable = true
part.headers = {}
part.name = null
part.filename = null
part.mime = null
part.transferEncoding = 'binary'
part.transferBuffer = ''
headerField = ''
headerValue = ''
}
parser.onHeaderField = function(b, start, end) {
headerField += b.toString(self.encoding, start, end)
}
parser.onHeaderValue = function(b, start, end) {
headerValue += b.toString(self.encoding, start, end)
}
parser.onHeaderEnd = function() {
headerField = headerField.toLowerCase()
part.headers[headerField] = headerValue
var m = headerValue.match(/\bname="([^"]+)"/i)
if (headerField == 'content-disposition') {
if (m) {
part.name = m[1]
}
part.filename = self._fileName(headerValue)
} else if (headerField == 'content-type') {
part.mime = headerValue
} else if (headerField == 'content-transfer-encoding') {
part.transferEncoding = headerValue.toLowerCase()
}
headerField = ''
headerValue = ''
}
parser.onHeadersEnd = function() {
switch (part.transferEncoding) {
case 'binary':
case '7bit':
case '8bit':
parser.onPartData = function(b, start, end) {
part.emit('data', b.slice(start, end))
}
parser.onPartEnd = function() {
part.emit('end')
}
break
case 'base64':
parser.onPartData = function(b, start, end) {
part.transferBuffer += b.slice(start, end).toString('ascii')
/*
four bytes (chars) in base64 converts to three bytes in binary
encoding. So we should always work with a number of bytes that
can be divided by 4, it will result in a number of buytes that
can be divided vy 3.
*/
var offset = parseInt(part.transferBuffer.length / 4, 10) * 4
part.emit(
'data',
Buffer.from(part.transferBuffer.substring(0, offset), 'base64')
)
part.transferBuffer = part.transferBuffer.substring(offset)
}
parser.onPartEnd = function() {
part.emit('data', Buffer.from(part.transferBuffer, 'base64'))
part.emit('end')
}
break
default:
return self._error(new Error('unknown transfer-encoding'))
}
self.onPart(part)
}
parser.onEnd = function() {
self.ended = true
self._maybeEnd()
}
this._parser = parser
}
IncomingForm.prototype._fileName = function(headerValue) {
var m = headerValue.match(/\bfilename="(.*?)"($|; )/i)
if (!m) return
var filename = m[1].substr(m[1].lastIndexOf('\\') + 1)
filename = filename.replace(/%22/g, '"') filename = filename.replace(/%22/g, '"')
filename = filename.replace(/&#([\d]{4});/g, function(m, code) { filename = filename.replace(/&#([\d]{4});/g, function (m, code) {
return String.fromCharCode(code) return String.fromCharCode(code)
}) })
return filename return filename
} }
IncomingForm.prototype._initUrlencoded = function() { /* ------------------------------------- */
this.type = 'urlencoded'
var parser = new QuerystringParser(this.maxFields) export default class IncomingForm extends EventEmitter {
#req = null
parser.onField = (key, val) => { #error = false
this.emit('field', key, val) #ended = false
ended = false
headers = null
bytesReceived = null
bytesExpected = null
#parser = null
#pending = 0
#openedFiles = []
constructor(req, opts = {}) {
super()
this.#req = req
this.uploadDir = opts.uploadDir
this.encoding = opts.encoding || 'utf-8'
this.headers = req.headers
this.#parseContentLength()
this.#parseContentType()
req
.on('error', err => {
this.#handleError(err)
this.#clearUploads()
})
.on('aborted', () => {
this.emit('aborted')
this.#clearUploads()
})
.on('data', buffer => this.#write(buffer))
.on('end', () => {
if (this.#error) {
return
}
let err = this.#parser.end()
if (err) {
this.#handleError(err)
}
})
} }
parser.onEnd = () => { #write(buffer) {
this.ended = true if (this.#error) {
this._maybeEnd() return
}
if (!this.#parser) {
return this.#handleError(new Error('uninitialized parser'))
}
this.bytesReceived += buffer.length
this.emit('progress', this.bytesReceived, this.bytesExpected)
this.#parser.write(buffer)
} }
this._parser = parser #handlePart(part) {
} if (part.filename === undefined) {
let value = Buffer.from('')
IncomingForm.prototype._initOctetStream = function() { part
this.type = 'octet-stream' .on('data', buff => {
var filename = this.headers['x-file-name'] value = Buffer.concat([value, buff])
var mime = this.headers['content-type'] })
.on('end', () => {
this.emit('field', part.name, value.toString(this.encoding))
})
} else {
let file = new File({
path: randomPath(this.uploadDir),
name: part.filename,
type: part.mime
})
var file = new File({ file.open()
path: this._uploadPath(filename),
name: filename,
type: mime
})
this.emit('fileBegin', filename, file) this.#openedFiles.push(file)
file.open() // 表单解析完的时候文件写入不一定完成了, 所以需要加入pending计数
this.#pending++
this._flushing++ part
.on('data', buffer => {
if (buffer.length == 0) {
return
}
file.write(buffer)
})
.on('end', () => {
if (part.ended) {
return
}
part.ended = true
file.end(() => {
this.emit('file', part.name, file)
this.#pending--
})
})
}
}
var self = this #parseContentType() {
let contentType = this.headers['content-type']
let lower = contentType.toLowerCase()
self._parser = new OctetParser() if (this.bytesExpected === 0) {
return (this.#parser = new EmptyParser())
}
//Keep track of writes that haven't finished so we don't emit the file before it's done being written if (lower.includes('octet-stream')) {
var outstandingWrites = 0 return this.#createStreamParser()
}
self._parser.on('data', function(buffer) { if (lower.includes('urlencoded')) {
self.pause() return this.#createUrlencodedParser()
outstandingWrites++ }
file.write(buffer, function() { if (lower.includes('multipart')) {
outstandingWrites-- let matches = contentType.match(/boundary=(?:"([^"]+)"|([^;]+))/)
self.resume() if (matches) {
this.#createMultipartParser(matches[1] || matches[2])
if (self.ended) { } else {
self._parser.emit('doneWritingFile') this.#handleError(new TypeError('unknow multipart boundary'))
} }
}) return
}) }
self._parser.on('end', function() { if (lower.match(/json|appliation|plain|text/)) {
self._flushing-- return this.#createJsonParser()
self.ended = true }
var done = function() { this.#handleError(new TypeError('unknown content-type: ' + contentType))
file.end(function() { }
self.emit('file', 'file', file)
self._maybeEnd() #parseContentLength() {
this.bytesReceived = 0
if (this.headers['content-length']) {
this.bytesExpected = +this.headers['content-length']
} else if (this.headers['transfer-encoding'] === undefined) {
this.bytesExpected = 0
}
}
#createMultipartParser(boundary) {
let headerField, headerValue, part
this.#parser = new MultipartParser(boundary)
this.#parser.$partBegin = function () {
part = new EventEmitter()
part.readable = true
part.headers = {}
part.name = null
part.filename = null
part.mime = null
part.transferEncoding = 'binary'
part.transferBuffer = ''
headerField = ''
headerValue = ''
}
this.#parser.$headerField = b => {
headerField += b.toString(this.encoding)
}
this.#parser.$headerValue = b => {
headerValue += b.toString(this.encoding)
}
this.#parser.$headerEnd = () => {
headerField = headerField.toLowerCase()
part.headers[headerField] = headerValue
let matches = headerValue.match(/\bname="([^"]+)"/i)
if (headerField == 'content-disposition') {
if (matches) {
part.name = matches[1]
}
part.filename = parseFilename(headerValue)
} else if (headerField == 'content-type') {
part.mime = headerValue
} else if (headerField == 'content-transfer-encoding') {
part.transferEncoding = headerValue.toLowerCase()
}
headerField = ''
headerValue = ''
}
this.#parser.$headersEnd = () => {
switch (part.transferEncoding) {
case 'binary':
case '7bit':
case '8bit':
this.#parser.$partData = function (b) {
part.emit('data', b)
}
this.#parser.$partEnd = function () {
part.emit('end')
}
break
case 'base64':
this.#parser.$partData = function (b) {
part.transferBuffer += b.toString('ascii')
// 确保offset的值能被4整除
let offset = ~~(part.transferBuffer.length / 4) * 4
part.emit(
'data',
Buffer.from(part.transferBuffer.slice(0, offset), 'base64')
)
part.transferBuffer = part.transferBuffer.slice(offset)
}
this.#parser.$partEnd = function () {
part.emit('data', Buffer.from(part.transferBuffer, 'base64'))
part.emit('end')
}
break
default:
return this.#handleError(new Error('unknown transfer-encoding'))
}
this.#handlePart(part)
}
this.#parser.$end = () => {
if (this.#pending > 0) {
setTimeout(_ => this.#parser.$end())
} else {
this.#handleEnd()
}
}
}
#createUrlencodedParser() {
this.#parser = new UrlencodedParser()
this.#parser
.on('field', fields => this.emit('field', false, fields))
.on('end', () => this.#handleEnd())
}
#createStreamParser() {
let filename = this.headers['x-file-name']
let mime = this.headers['x-file-type']
this.#parser = new OctetParser(filename, mime, randomPath(this.uploadDir))
if (this.bytesExpected) {
this.#parser.initLength(this.bytesExpected)
}
this.#parser
.on('file', file => {
this.emit('file', false, file)
})
.on('end', () => this.#handleEnd())
.on('error', err => this.#handleError(err))
}
#createJsonParser() {
this.#parser = new JSONParser()
if (this.bytesExpected) {
this.#parser.initLength(this.bytesExpected)
}
this.#parser
.on('field', (key, val) => {
this.emit('field', key, val)
})
.on('end', () => this.#handleEnd())
.on('error', err => this.#handleError(err))
}
#clearUploads() {
while (this.#openedFiles.length) {
let file = this.#openedFiles.pop()
file._writeStream.destroy()
setTimeout(_ => {
try {
fs.unlink(file.path)
} catch (e) {}
}) })
} }
}
if (outstandingWrites === 0) { #handleError(err) {
done() if (this.#error || this.#ended) {
} else { return
self._parser.once('doneWritingFile', done)
} }
}) this.error = true
} this.emit('error', err)
}
IncomingForm.prototype._initJSONencoded = function() {
this.type = 'json' #handleEnd() {
if (this.#ended || this.#error) {
var parser = new JSONParser(), return
self = this }
this.#ended = true
if (this.bytesExpected) { this.emit('end')
parser.initWithLength(this.bytesExpected) }
}
parser.onField = function(key, val) {
self.emit('field', key, val)
}
parser.onEnd = function() {
self.ended = true
self._maybeEnd()
}
this._parser = parser
}
IncomingForm.prototype._uploadPath = function(filename) {
var name = 'upload_'
var buf = crypto.randomBytes(16)
for (var i = 0; i < buf.length; ++i) {
name += ('0' + buf[i].toString(16)).slice(-2)
}
if (this.keepExtensions) {
var ext = path.extname(filename)
ext = ext.replace(/(\.[a-z0-9]+).*/i, '$1')
name += ext
}
return path.join(this.uploadDir, name)
}
IncomingForm.prototype._maybeEnd = function() {
if (!this.ended || this._flushing || this.error) {
return
}
this.emit('end')
} }

View File

@ -1,33 +1,43 @@
export function JSONParser() { import { EventEmitter } from 'node:events'
this.data = Buffer.from('')
this.bytesWritten = 0
}
JSONParser.prototype.initWithLength = function(length) { export class JSONParser extends EventEmitter {
this.data = Buffer.alloc(length) #buff = Buffer.from('')
} #byteLen = 0
JSONParser.prototype.write = function(buffer) { initLength(length) {
if (this.data.length >= this.bytesWritten + buffer.length) { this.#byteLen = length
buffer.copy(this.data, this.bytesWritten)
} else {
this.data = Buffer.concat([this.data, buffer])
}
this.bytesWritten += buffer.length
return buffer.length
}
JSONParser.prototype.end = function() {
var data = this.data.toString('utf8')
var fields
try {
fields = JSON.parse(data)
} catch (e) {
fields = Function(`try{return ${data}}catch(e){}`)() || data
} }
this.onField(false, fields) write(buffer) {
this.data = null this.#buff = Buffer.concat([this.#buff, buffer])
}
this.onEnd() end() {
if (this.#buff.length === this.#byteLen) {
let data = this.#buff.toString()
let fields = data
try {
fields = JSON.parse(data)
} catch (e) {
try {
// 非标准的json语法,尝试用 Function 解析
fields = Function(`try{return ${data}}catch(e){}`)()
} catch (err) {}
}
this.emit('field', false, fields)
this.emit('end')
this.#buff = null
} else {
this.emit(
'error',
new Error(
`The uploaded data is incomplete. Expected ${
this.#byteLen
}, Received ${this.#buff.length} .`
)
)
}
}
} }

View File

@ -1,327 +1,335 @@
var s = 0, /**
S = { * {}
PARSER_UNINITIALIZED: s++, * @author yutent<yutent.io@gmail.com>
START: s++, * @date 2023/10/30 16:41:59
START_BOUNDARY: s++, */
HEADER_FIELD_START: s++,
HEADER_FIELD: s++,
HEADER_VALUE_START: s++,
HEADER_VALUE: s++,
HEADER_VALUE_ALMOST_DONE: s++,
HEADERS_ALMOST_DONE: s++,
PART_DATA_START: s++,
PART_DATA: s++,
PART_END: s++,
END: s++
},
f = 1,
F = {
PART_BOUNDARY: f,
LAST_BOUNDARY: (f *= 2)
},
LF = 10,
CR = 13,
SPACE = 32,
HYPHEN = 45,
COLON = 58,
A = 97,
Z = 122,
lower = function(c) {
return c | 0x20
}
export function MultipartParser() { let s = 0
this.boundary = null const STATE_DICT = {
this.boundaryChars = null PARSER_UNINITIALIZED: s++,
this.lookbehind = null START: s++,
this.state = S.PARSER_UNINITIALIZED START_BOUNDARY: s++,
HEADER_FIELD_START: s++,
this.index = null HEADER_FIELD: s++,
this.flags = 0 HEADER_VALUE_START: s++,
HEADER_VALUE: s++,
HEADER_VALUE_ALMOST_DONE: s++,
HEADERS_ALMOST_DONE: s++,
PART_DATA_START: s++,
PART_DATA: s++,
PART_END: s++,
END: s++
}
let f = 1
const FLAG_DICT = {
PART_BOUNDARY: f,
LAST_BOUNDARY: (f *= 2)
} }
MultipartParser.stateToString = function(stateNumber) { const LF = 10
for (var state in S) { const CR = 13
var number = S[state] const SPACE = 32
if (number === stateNumber) return state const HYPHEN = 45
} const COLON = 58
const LETTER_A = 97
const LETTER_Z = 122
function lower(c) {
return c | 0x20
} }
MultipartParser.prototype.initWithBoundary = function(str) { function stateToString(value) {
this.boundary = Buffer.alloc(str.length + 4) for (let key in STATE_DICT) {
this.boundary.write('\r\n--', 0) let number = STATE_DICT[key]
this.boundary.write(str, 4) if (number === value) {
this.lookbehind = Buffer.alloc(this.boundary.length + 8) return key
this.state = S.START
this.boundaryChars = {}
for (var i = 0; i < this.boundary.length; i++) {
this.boundaryChars[this.boundary[i]] = true
}
}
MultipartParser.prototype.write = function(buffer) {
var self = this,
i = 0,
len = buffer.length,
prevIndex = this.index,
index = this.index,
state = this.state,
flags = this.flags,
lookbehind = this.lookbehind,
boundary = this.boundary,
boundaryChars = this.boundaryChars,
boundaryLength = this.boundary.length,
boundaryEnd = boundaryLength - 1,
bufferLength = buffer.length,
c,
cl,
mark = function(name) {
self[name + 'Mark'] = i
},
clear = function(name) {
delete self[name + 'Mark']
},
callback = function(name, buffer, start, end) {
if (start !== undefined && start === end) {
return
}
var callbackSymbol =
'on' + name.substr(0, 1).toUpperCase() + name.substr(1)
if (callbackSymbol in self) {
self[callbackSymbol](buffer, start, end)
}
},
dataCallback = function(name, clear) {
var markSymbol = name + 'Mark'
if (!(markSymbol in self)) {
return
}
if (!clear) {
callback(name, buffer, self[markSymbol], buffer.length)
self[markSymbol] = 0
} else {
callback(name, buffer, self[markSymbol], i)
delete self[markSymbol]
}
} }
}
}
for (i = 0; i < len; i++) { export class MultipartParser {
c = buffer[i] boundary = null
switch (state) { boundaryChars = null
case S.PARSER_UNINITIALIZED: lookbehind = null
return i state = STATE_DICT.PARSER_UNINITIALIZED
case S.START:
index = 0
state = S.START_BOUNDARY
case S.START_BOUNDARY:
if (index == boundary.length - 2) {
if (c == HYPHEN) {
flags |= F.LAST_BOUNDARY
} else if (c != CR) {
return i
}
index++
break
} else if (index - 1 == boundary.length - 2) {
if (flags & F.LAST_BOUNDARY && c == HYPHEN) {
callback('end')
state = S.END
flags = 0
} else if (!(flags & F.LAST_BOUNDARY) && c == LF) {
index = 0
callback('partBegin')
state = S.HEADER_FIELD_START
} else {
return i
}
break
}
if (c != boundary[index + 2]) { index = null
index = -2 flags = 0
}
if (c == boundary[index + 2]) {
index++
}
break
case S.HEADER_FIELD_START:
state = S.HEADER_FIELD
mark('headerField')
index = 0
case S.HEADER_FIELD:
if (c == CR) {
clear('headerField')
state = S.HEADERS_ALMOST_DONE
break
}
index++ constructor(str) {
if (c == HYPHEN) { this.boundary = Buffer.alloc(str.length + 4)
break this.boundary.write('\r\n--', 0)
} this.boundary.write(str, 4)
this.lookbehind = Buffer.alloc(this.boundary.length + 8)
this.state = STATE_DICT.START
if (c == COLON) { this.boundaryChars = {}
if (index == 1) { for (let i = 0; i < this.boundary.length; i++) {
// empty header field this.boundaryChars[this.boundary[i]] = true
return i }
} }
dataCallback('headerField', true)
state = S.HEADER_VALUE_START
break
}
cl = lower(c) #mark(k, v) {
if (cl < A || cl > Z) { this[k + 'Mark'] = v
return i }
}
break
case S.HEADER_VALUE_START:
if (c == SPACE) {
break
}
mark('headerValue') #emit(name, buff, idx, cleanup) {
state = S.HEADER_VALUE let mark = name + 'Mark'
case S.HEADER_VALUE: if (this[mark] !== void 0) {
if (c == CR) { let start = this[mark]
dataCallback('headerValue', true) let end = buff.length
callback('headerEnd')
state = S.HEADER_VALUE_ALMOST_DONE
}
break
case S.HEADER_VALUE_ALMOST_DONE:
if (c != LF) {
return i
}
state = S.HEADER_FIELD_START
break
case S.HEADERS_ALMOST_DONE:
if (c != LF) {
return i
}
callback('headersEnd') if (cleanup) {
state = S.PART_DATA_START end = idx
break delete this[mark]
case S.PART_DATA_START: } else {
state = S.PART_DATA this[mark] = 0
mark('partData') }
case S.PART_DATA:
prevIndex = index
if (index === 0) { if (start === end) {
// boyer-moore derrived algorithm to safely skip non-boundary data return
i += boundaryEnd }
while (i < bufferLength && !(buffer[i] in boundaryChars)) { this['$' + name](buff.slice(start, end))
i += boundaryLength }
} }
i -= boundaryEnd
c = buffer[i]
}
if (index < boundary.length) { write(buffer) {
if (boundary[index] == c) { let idx = 0,
if (index === 0) { len = buffer.length,
dataCallback('partData', true) prevIndex = this.index,
index = this.index,
state = this.state,
flags = this.flags,
lookbehind = this.lookbehind,
boundary = this.boundary,
boundaryChars = this.boundaryChars,
boundaryLength = this.boundary.length,
boundaryEnd = boundaryLength - 1,
bufferLength = buffer.length,
c,
cl
for (idx = 0; idx < len; idx++) {
c = buffer[idx]
switch (state) {
case STATE_DICT.PARSER_UNINITIALIZED:
return
case STATE_DICT.START:
index = 0
state = STATE_DICT.START_BOUNDARY
case STATE_DICT.START_BOUNDARY:
if (index == boundary.length - 2) {
if (c == HYPHEN) {
flags |= FLAG_DICT.LAST_BOUNDARY
} else if (c != CR) {
return
} }
index++ index++
} else { break
index = 0 } else if (index - 1 == boundary.length - 2) {
} if (flags & FLAG_DICT.LAST_BOUNDARY && c == HYPHEN) {
} else if (index == boundary.length) { this.$end()
index++ state = STATE_DICT.END
if (c == CR) {
// CR = part boundary
flags |= F.PART_BOUNDARY
} else if (c == HYPHEN) {
// HYPHEN = end boundary
flags |= F.LAST_BOUNDARY
} else {
index = 0
}
} else if (index - 1 == boundary.length) {
if (flags & F.PART_BOUNDARY) {
index = 0
if (c == LF) {
// unset the PART_BOUNDARY flag
flags &= ~F.PART_BOUNDARY
callback('partEnd')
callback('partBegin')
state = S.HEADER_FIELD_START
break
}
} else if (flags & F.LAST_BOUNDARY) {
if (c == HYPHEN) {
callback('partEnd')
callback('end')
state = S.END
flags = 0 flags = 0
} else if (!(flags & FLAG_DICT.LAST_BOUNDARY) && c == LF) {
index = 0
this.$partBegin()
state = STATE_DICT.HEADER_FIELD_START
} else {
return
}
break
}
if (c != boundary[index + 2]) {
index = -2
}
if (c == boundary[index + 2]) {
index++
}
break
case STATE_DICT.HEADER_FIELD_START:
state = STATE_DICT.HEADER_FIELD
this.#mark('headerField', idx)
index = 0
case STATE_DICT.HEADER_FIELD:
if (c == CR) {
delete this.headerFieldMark
state = STATE_DICT.HEADERS_ALMOST_DONE
break
}
index++
if (c == HYPHEN) {
break
}
if (c == COLON) {
if (index == 1) {
// empty header field
return
}
this.#emit('headerField', buffer, idx, true)
state = STATE_DICT.HEADER_VALUE_START
break
}
cl = lower(c)
if (cl < LETTER_A || cl > LETTER_Z) {
return
}
break
case STATE_DICT.HEADER_VALUE_START:
if (c == SPACE) {
break
}
this.#mark('headerValue', idx)
state = STATE_DICT.HEADER_VALUE
case STATE_DICT.HEADER_VALUE:
if (c == CR) {
this.#emit('headerValue', buffer, idx, true)
this.$headerEnd()
state = STATE_DICT.HEADER_VALUE_ALMOST_DONE
}
break
case STATE_DICT.HEADER_VALUE_ALMOST_DONE:
if (c != LF) {
return
}
state = STATE_DICT.HEADER_FIELD_START
break
case STATE_DICT.HEADERS_ALMOST_DONE:
if (c != LF) {
return
}
this.$headersEnd()
state = STATE_DICT.PART_DATA_START
break
case STATE_DICT.PART_DATA_START:
state = STATE_DICT.PART_DATA
this.#mark('partData', idx)
case STATE_DICT.PART_DATA:
prevIndex = index
if (index === 0) {
// boyer-moore derrived algorithm to safely skip non-boundary data
idx += boundaryEnd
while (idx < bufferLength && !(buffer[idx] in boundaryChars)) {
idx += boundaryLength
}
idx -= boundaryEnd
c = buffer[idx]
}
if (index < boundary.length) {
if (boundary[index] == c) {
if (index === 0) {
this.#emit('partData', buffer, idx, true)
}
index++
} else {
index = 0
}
} else if (index == boundary.length) {
index++
if (c == CR) {
// CR = part boundary
flags |= FLAG_DICT.PART_BOUNDARY
} else if (c == HYPHEN) {
// HYPHEN = end boundary
flags |= FLAG_DICT.LAST_BOUNDARY
} else {
index = 0
}
} else if (index - 1 == boundary.length) {
if (flags & FLAG_DICT.PART_BOUNDARY) {
index = 0
if (c == LF) {
// unset the PART_BOUNDARY flag
flags &= ~FLAG_DICT.PART_BOUNDARY
this.$partEnd()
this.$partBegin()
state = STATE_DICT.HEADER_FIELD_START
break
}
} else if (flags & FLAG_DICT.LAST_BOUNDARY) {
if (c == HYPHEN) {
this.$partEnd()
this.$end()
state = STATE_DICT.END
flags = 0
} else {
index = 0
}
} else { } else {
index = 0 index = 0
} }
} else {
index = 0
} }
}
if (index > 0) { if (index > 0) {
// when matching a possible boundary, keep a lookbehind reference // when matching a possible boundary, keep a lookbehind reference
// in case it turns out to be a false lead // in case it turns out to be a false lead
lookbehind[index - 1] = c lookbehind[index - 1] = c
} else if (prevIndex > 0) { } else if (prevIndex > 0) {
// if our boundary turned out to be rubbish, the captured lookbehind // if our boundary turned out to be rubbish, the captured lookbehind
// belongs to partData // belongs to partData
callback('partData', lookbehind, 0, prevIndex)
prevIndex = 0
mark('partData')
// reconsider the current character even so it interrupted the sequence this.$partData(lookbehind.slice(0, prevIndex))
// it could be the beginning of a new sequence prevIndex = 0
i-- this.#mark('partData', idx)
}
break // reconsider the current character even so it interrupted the sequence
case S.END: // it could be the beginning of a new sequence
break idx--
default: }
return i
break
case STATE_DICT.END:
break
default:
return
}
}
this.#emit('headerField', buffer, idx)
this.#emit('headerValue', buffer, idx)
this.#emit('partData', buffer, idx)
this.index = index
this.state = state
this.flags = flags
}
end() {
if (
(this.state === STATE_DICT.HEADER_FIELD_START && this.index === 0) ||
(this.state === STATE_DICT.PART_DATA &&
this.index == this.boundary.length)
) {
this.$end()
} else if (this.state !== STATE_DICT.END) {
return new Error(
'MultipartParser.end(): stream ended unexpectedly: ' + this.explain()
)
} }
} }
dataCallback('headerField') explain() {
dataCallback('headerValue') return 'state = ' + stateToString(this.state)
dataCallback('partData')
this.index = index
this.state = state
this.flags = flags
return len
}
MultipartParser.prototype.end = function() {
var callback = function(self, name) {
var callbackSymbol = 'on' + name.substr(0, 1).toUpperCase() + name.substr(1)
if (callbackSymbol in self) {
self[callbackSymbol]()
}
}
if (
(this.state == S.HEADER_FIELD_START && this.index === 0) ||
(this.state == S.PART_DATA && this.index == this.boundary.length)
) {
callback(this, 'partEnd')
callback(this, 'end')
} else if (this.state != S.END) {
return new Error(
'MultipartParser.end(): stream ended unexpectedly: ' + this.explain()
)
} }
} }
MultipartParser.prototype.explain = function() {
return 'state = ' + MultipartParser.stateToString(this.state)
}

View File

@ -1,17 +1,56 @@
import { EventEmitter } from 'events' /**
import util from 'util' * {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/10/27 14:23:22
*/
export function OctetParser() { import { EventEmitter } from 'node:events'
EventEmitter.call(this) 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} .`
)
)
}
})
}
} }
util.inherits(OctetParser, EventEmitter) export class EmptyParser extends EventEmitter {
write() {}
OctetParser.prototype.write = function(buffer) { end() {
this.emit('data', buffer) this.emit('end')
return buffer.length }
}
OctetParser.prototype.end = function() {
this.emit('end')
} }

View File

@ -1,27 +0,0 @@
// This is a buffering parser, not quite as nice as the multipart one.
// If I find time I'll rewrite this to be fully streaming as well
import querystring from 'querystring'
export class QuerystringParser {
constructor(maxKeys) {
this.maxKeys = maxKeys
this.buffer = ''
}
write(buffer) {
this.buffer += buffer.toString('ascii')
return buffer.length
}
end() {
var fields = querystring.parse(this.buffer, '&', '=', {
maxKeys: this.maxKeys
})
for (var field in fields) {
this.onField(field, fields[field])
}
this.buffer = ''
this.onEnd()
}
}

26
lib/urlencoded_parser.js Normal file
View File

@ -0,0 +1,26 @@
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/10/27 12:14:05
*/
import { parse } from 'node:querystring'
import { EventEmitter } from 'node:events'
export class UrlencodedParser extends EventEmitter {
#buff = Buffer.from('')
write(buffer) {
this.#buff = Buffer.concat([this.#buff, buffer])
}
end() {
let data = this.#buff.toString()
let fields = parse(data)
this.#buff = null
this.emit('field', fields)
this.emit('end')
}
}

View File

@ -1,13 +1,14 @@
{ {
"name": "@gm5/request", "name": "@gm5/request",
"version": "1.2.8", "version": "2.0.0",
"description": "对Http的request进一步封装, 提供常用的API", "description": "对Http的Request进一步封装, 提供常用的API",
"main": "index.js", "main": "index.js",
"author": "yutent", "author": "yutent",
"type": "module", "type": "module",
"keywords": [ "keywords": [
"five", "five",
"node-five", "gmf",
"gm5",
"five.js", "five.js",
"fivejs", "fivejs",
"request", "request",