Skip to content

Commit c68d7b8

Browse files
authored
Merge pull request m4nuC#53 from alqu/master
Update internal busboy from v0.3.1 to v1.4.0
2 parents 3da5e7e + 63c2d2e commit c68d7b8

File tree

9 files changed

+2869
-1025
lines changed

9 files changed

+2869
-1025
lines changed

.gitignore

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
.DS_Store
2-
node_modules
2+
.nyc_output
33
coverage
4-
npm-debug.log
4+
node_modules
5+
npm-debug.log

.prettierignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Ignore artifacts:
2+
coverage

.travis.yml

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
sudo: false
22
node_js:
3-
- "10"
3+
- '10'
44
language: node_js
5-
script: "npm run cover"
6-
after_script: "npm i codecov.io && cat ./coverage/coverage.json | ./node_modules/codecov.io/bin/codecov.io.js"
5+
script: 'npm run cover'
6+
after_script: 'npm i codecov.io && cat ./coverage/coverage.json | ./node_modules/codecov.io/bin/codecov.io.js'

README.md

+40-28
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# Promise Based Multipart Form Parser
22

3-
43
[![NPM version][npm-image]][npm-url]
54
[![build status][travis-image]][travis-url]
65
[![Test coverage][codecov-image]][codecov-url]
@@ -22,56 +21,62 @@ Designed for use with [Koa2](https://github.com/koajs/koa/tree/v2.x) and [Async/
2221
## Examples
2322

2423
### Async/Await (using temp files)
24+
2525
```js
2626
import asyncBusboy from 'async-busboy';
2727

2828
// Koa 2 middleware
29-
async function(ctx, next) {
30-
const {files, fields} = await asyncBusboy(ctx.req);
29+
async function someFunction(ctx, next) {
30+
const { files, fields } = await asyncBusboy(ctx.req);
3131

3232
// Make some validation on the fields before upload to S3
33-
if ( checkFiles(fields) ) {
34-
files.map(uploadFilesToS3)
33+
if (checkFiles(fields)) {
34+
files.map(uploadFilesToS3);
3535
} else {
3636
return 'error';
3737
}
3838
}
3939
```
40+
4041
### Async/Await (using custom onFile handler, i.e. no temp files)
42+
4143
```js
4244
import asyncBusboy from 'async-busboy';
4345

4446
// Koa 2 middleware
45-
async function(ctx, next) {
46-
 const { fields } = await asyncBusboy(ctx.req, {
47-
onFile: function(fieldname, file, filename, encoding, mimetype) {
47+
async function someFunction(ctx, next) {
48+
const { fields } = await asyncBusboy(ctx.req, {
49+
onFile: function (fieldname, file, filename, encoding, mimetype) {
4850
uploadFilesToS3(file);
49-
}
51+
},
5052
});
5153

5254
// Do validation, but files are already uploading...
53-
if ( !checkFiles(fields) ) {
55+
if (!checkFiles(fields)) {
5456
return 'error';
5557
}
5658
}
5759
```
5860

5961
### ES5 with promise (using temp files)
62+
6063
```js
6164
var asyncBusboy = require('async-busboy');
6265

63-
function(someHTTPRequest) {
64-
asyncBusboy(someHTTPRequest).then(function(formData) {
66+
function someFunction(someHTTPRequest) {
67+
asyncBusboy(someHTTPRequest).then(function (formData) {
6568
// do something with formData.files
6669
// do someting with formData.fields
6770
});
6871
}
6972
```
7073

7174
## Async API using temp files
75+
7276
The request streams are first written to temporary files using `os.tmpdir()`. File read streams associated with the temporary files are returned from the call to async-busboy. When the consumer has drained the file read streams, the files will be automatically removed, otherwise the host OS should take care of the cleaning process.
7377

7478
## Async API using custom onFile handler
79+
7580
If a custom onFile handler is specified in the options to async-busboy it
7681
will only resolve an object containing fields, but instead no temporary files
7782
needs to be created since the file stream is directly passed to the application.
@@ -80,22 +85,25 @@ to the implementation of busboy. If you don't care about a received
8085
file stream, simply call `stream.resume()` to discard the content.
8186

8287
## Working with nested inputs and objects
88+
8389
Make sure to serialize objects before sending them as formData.
8490
i.e:
85-
```js
91+
92+
```json5
8693
// Given an object that represent the form data:
8794
{
88-
'field1': 'value',
89-
'objectField': {
90-
'key': 'anotherValue'
95+
field1: 'value',
96+
objectField: {
97+
key: 'anotherValue',
9198
},
92-
'arrayField': ['a', 'b']
99+
arrayField: ['a', 'b'],
93100
//...
94-
};
101+
}
95102
```
96103

97104
Should be sent as:
98-
```
105+
106+
```js
99107
// -> field1[value]
100108
// -> objectField[key][anotherKey]
101109
// -> arrayField[0]['a']
@@ -104,22 +112,27 @@ Should be sent as:
104112
```
105113

106114
Here is a function that can take care of this process
115+
107116
```js
108117
const serializeFormData = (obj, formDataObj, namespace = null) => {
109118
var formDataObj = formDataObj || {};
110119
var formKey;
111-
for(var property in obj) {
112-
if(obj.hasOwnProperty(property)) {
113-
if(namespace) {
120+
for (var property in obj) {
121+
if (obj.hasOwnProperty(property)) {
122+
if (namespace) {
114123
formKey = namespace + '[' + property + ']';
115124
} else {
116125
formKey = property;
117126
}
118127

119128
var value = obj[property];
120-
if(typeof value === 'object' && !(value instanceof File) && !(value instanceof Date)) {
121-
serializeFormData(value, formDataObj, formKey);
122-
} else if(value instanceof Date) {
129+
if (
130+
typeof value === 'object' &&
131+
!(value instanceof File) &&
132+
!(value instanceof Date)
133+
) {
134+
serializeFormData(value, formDataObj, formKey);
135+
} else if (value instanceof Date) {
123136
formDataObj[formKey] = value.toISOString();
124137
} else {
125138
formDataObj[formKey] = value;
@@ -132,12 +145,11 @@ const serializeFormData = (obj, formDataObj, namespace = null) => {
132145
// -->
133146
```
134147

135-
136148
### Try it on your local
149+
137150
If you want to run some test locally, clone this repo, then run: `node examples/index.js`
138151
From there you can use something like [Postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en) to send `POST` request to `localhost:8080`.
139-
Note: When using Postman make sure to not send a `Content-Type` header, if it's filed by default, just delete it. (This is to let the `boudary` header be generated automaticaly)
140-
152+
Note: When using Postman make sure to not send a `Content-Type` header, if it's filed by default, just delete it. (This is to let the `boudary` header be generated automatically)
141153

142154
### Use cases:
143155

examples/index.js

+60-19
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,67 @@
1-
//This file is if you want to run some test localy, run: `node index.js`
2-
//From there you can use something like [Postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en) to send `POST` request to `localhost:8080`.
3-
//Note: When using Postman make sure to not send a `Content-Type` header, if it's field by default, juste delete it.
1+
// This file is if you want to run some test locally, run: `node index.js`
2+
// From there you can use something like [Postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en) to send `POST` request to `localhost:8080`.
3+
// Note: When using Postman make sure to not send a `Content-Type` header, if it's field by default, juste delete it.
44

5-
const asyncBusboy = require('../')
5+
const asyncBusboy = require('../');
66
const http = require('http');
77
const PORT = 8080;
88

9-
function handleRequest(request, response){
10-
asyncBusboy(request).then(function(formData) {
11-
// [You can put your tests here]
12-
console.log('Files :', formData.files);
13-
console.log('Fields :', formData.fields)
9+
const server = http
10+
.createServer((req, res) => {
11+
if (req.method === 'POST') {
12+
console.log('POST request');
13+
asyncBusboy(req).then(
14+
function (formData) {
15+
// [You can put your tests here]
16+
console.log('Files :', formData.files);
17+
console.log('Fields :', formData.fields);
1418

15-
// We need to emit a reponse so that the request doesn't hang
16-
response.end('It Works!! ');
17-
},function(error) {
18-
console.log(error)
19-
response.end('Something broke!! ');
19+
// We need to emit a response so that the request doesn't hang
20+
res.end('It Works!! ');
21+
},
22+
function (error) {
23+
console.log(error);
24+
res.end('Something broke!! ');
25+
}
26+
);
27+
} else if (req.method === 'GET') {
28+
res.writeHead(200, { Connection: 'close' });
29+
res.end(`
30+
<!doctype html>
31+
<html lang="en">
32+
<head>
33+
<meta name="viewport" content="width=device-width, initial-scale=1">
34+
<title>Async Busboy upload test</title>
35+
<link rel="stylesheet" href="//unpkg.com/@picocss/pico@latest/css/pico.classless.min.css">
36+
</head>
37+
<body>
38+
<main>
39+
<h1>Async Busboy upload test</h1>
40+
<form method="POST" enctype="multipart/form-data">
41+
<label>
42+
Choose file for upload
43+
<input type="file" name="filefield">
44+
</label>
45+
<label>
46+
A text field
47+
<input type="text" name="textfield" placeholder="a text field">
48+
</label>
49+
<button type="submit">Submit</button>
50+
</form>
51+
</main>
52+
</body>
53+
</html>
54+
`);
55+
}
56+
})
57+
.listen(PORT, () => {
58+
console.log('Server listening on: http://localhost:%s', PORT);
2059
});
21-
}
2260

23-
var server = http.createServer(handleRequest);
24-
server.listen(PORT, function(){
25-
console.log("Server listening on: http://localhost:%s", PORT);
26-
});
61+
// Example output:
62+
//
63+
// Server listening on: http://localhost:8080
64+
// < ... form submitted ... >
65+
// POST request
66+
// Files : [ ...
67+
// Fields : { textfield: '...' }

0 commit comments

Comments
 (0)