Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ yarn-debug.log*
yarn-error.log*
lerna-debug.log*

yarn.lock

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

Expand Down
21 changes: 21 additions & 0 deletions demos/with-upload-file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const multer = require('multer')
const { router, server } = require('0http')({
server: require('../src/server')()
})

const upload = multer({
storage: multer.diskStorage({
destination: __dirname,
filename: (req, file, cb) => cb(null, file.originalname)
})
})

router.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
res.statusCode = 400
res.end('Failed to upload')
}
res.end('Success upload ' + req.file.originalname)
})

server.listen(3000, () => { })
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"body-parser": "^1.19.0",
"chai": "^4.2.0",
"mocha": "^7.2.0",
"multer": "^1.4.2",
"nyc": "^15.1.0",
"restana": "^4.8.1",
"supertest": "^4.0.2"
Expand Down
13 changes: 8 additions & 5 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,21 @@ module.exports = (config = {}) => {

const method = reqWrapper.method
if (method !== 'HEAD') { // 0http's low checks also that method !== 'GET', but many users would send request body with GET, unfortunately
let buffer
res.onData((bytes, isLast) => {
const chunk = Buffer.from(bytes)
if (!bytes.byteLength) return handler(reqWrapper, resWrapper)
let chunk = Buffer.from(bytes)
if (isLast) {
if (buffer) chunk = Buffer.concat([buffer, chunk])
reqWrapper.push(chunk)
reqWrapper.push(null)
if (!res.finished) {
return handler(reqWrapper, resWrapper)
}
return
} else {
if (buffer) buffer = Buffer.concat([buffer, chunk])
else buffer = Buffer.concat([chunk])
}

return reqWrapper.push(chunk)
})
} else if (!res.finished) {
handler(reqWrapper, resWrapper)
Expand Down Expand Up @@ -112,7 +115,7 @@ class HttpRequest extends Readable {
}

_read (size) {
return this.slice(0, size)
return this.slice ? this.slice(0, size) : size
}
}

Expand Down