forked from yahoo/express-busboy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
89 lines (80 loc) · 2.98 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
* Copyright (c) 2014, Yahoo Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
var busboy = require('connect-busboy'),
key = '@express-busboy',
path = require('path'),
uuid = require('uuid'),
fs = require('fs'),
mkdirp = require('mkdirp'),
qs = require('qs'),
os = require('os'),
jsonBody = require('body/json');
exports.extend = function(app, options) {
if (app[key]) { return app; }
Object.defineProperty(app, key, { value: exports });
options = options || {};
options.immediate = false; //Remove if the user sets it
options.path = options.path || path.join(os.tmpdir(), 'express-busboy');
app.use(busboy(options));
app.use(function(req, res, next) {
req.body = {};
req.files = {};
if (req.is('json')) {
jsonBody(req, res, options, function(err, body) {
req.body = body || {};
next();
});
} else {
if (!req.busboy) { //Nothing to parse..
return next();
}
if (options.upload) {
req.busboy.on('file', function(name, file, filename, encoding, mimetype) {
var fileUuid = uuid.v4(),
out = path.join(options.path, '/', fileUuid, '/', name, filename);
mkdirp.sync(path.dirname(out));
var writer = fs.createWriteStream(out);
file.pipe(writer);
var data = {
uuid: fileUuid,
field: name,
file: out,
filename: filename,
encoding: encoding,
mimetype: mimetype,
truncated: false
};
// Indicate whether the file was truncated
file.on('limit', function() {
data.truncated = true;
});
if (Array.isArray(req.files[name])) {
req.files[name].push(data);
} else if (req.files[name]) {
req.files[name] = [req.files[name], data];
} else {
req.files[name] = data;
}
});
}
req.busboy.on('field', function(fieldname, val) {
if (Array.isArray(req.body[fieldname])) {
req.body[fieldname].push(val);
} else if (req.body[fieldname]) {
req.body[fieldname] = [req.body[fieldname], val];
} else {
req.body[fieldname] = val;
}
});
req.busboy.on('finish', function() {
req.body = qs.parse(qs.stringify(req.body));
next();
});
req.pipe(req.busboy);
}
});
return app;
};