1 | var Busboy = require('..');
|
2 |
|
3 | var path = require('path');
|
4 | var inspect = require('util').inspect;
|
5 | var assert = require('assert');
|
6 |
|
7 | function formDataSection(key, value) {
|
8 | return Buffer.from('\r\n--' + BOUNDARY
|
9 | + '\r\nContent-Disposition: form-data; name="'
|
10 | + key + '"\r\n\r\n' + value);
|
11 | }
|
12 | function formDataFile(key, filename, contentType) {
|
13 | return Buffer.concat([
|
14 | Buffer.from('\r\n--' + BOUNDARY + '\r\n'),
|
15 | Buffer.from('Content-Disposition: form-data; name="'
|
16 | + key + '"; filename="' + filename + '"\r\n'),
|
17 | Buffer.from('Content-Type: ' + contentType + '\r\n\r\n'),
|
18 | Buffer.allocUnsafe(100000)
|
19 | ]);
|
20 | }
|
21 |
|
22 | var BOUNDARY = 'u2KxIV5yF1y+xUspOQCCZopaVgeV6Jxihv35XQJmuTx8X3sh';
|
23 | var reqChunks = [
|
24 | Buffer.concat([
|
25 | formDataFile('file', 'file.bin', 'application/octet-stream'),
|
26 | formDataSection('foo', 'foo value')
|
27 | ]),
|
28 | formDataSection('bar', 'bar value'),
|
29 | Buffer.from('\r\n--' + BOUNDARY + '--\r\n')
|
30 | ];
|
31 | var busboy = new Busboy({
|
32 | headers: {
|
33 | 'content-type': 'multipart/form-data; boundary=' + BOUNDARY
|
34 | }
|
35 | });
|
36 | var finishes = 0;
|
37 | var results = [];
|
38 | var expected = [
|
39 | ['file', 'file', 'file.bin', '7bit', 'application/octet-stream'],
|
40 | ['field', 'foo', 'foo value', false, false, '7bit', 'text/plain'],
|
41 | ['field', 'bar', 'bar value', false, false, '7bit', 'text/plain'],
|
42 | ];
|
43 |
|
44 | busboy.on('field', function(key, val, keyTrunc, valTrunc, encoding, contype) {
|
45 | results.push(['field', key, val, keyTrunc, valTrunc, encoding, contype]);
|
46 | });
|
47 | busboy.on('file', function(fieldname, stream, filename, encoding, mimeType) {
|
48 | results.push(['file', fieldname, filename, encoding, mimeType]);
|
49 |
|
50 |
|
51 | setTimeout(function() {
|
52 | stream.resume();
|
53 | }, 10);
|
54 | });
|
55 | busboy.on('finish', function() {
|
56 | assert(finishes++ === 0, 'finish emitted multiple times');
|
57 | assert.deepEqual(results.length,
|
58 | expected.length,
|
59 | 'Parsed result count mismatch. Saw '
|
60 | + results.length
|
61 | + '. Expected: ' + expected.length);
|
62 |
|
63 | results.forEach(function(result, i) {
|
64 | assert.deepEqual(result,
|
65 | expected[i],
|
66 | 'Result mismatch:\nParsed: ' + inspect(result)
|
67 | + '\nExpected: ' + inspect(expected[i]));
|
68 | });
|
69 | }).on('error', function(err) {
|
70 | assert(false, 'Unexpected error: ' + err.stack);
|
71 | });
|
72 |
|
73 | reqChunks.forEach(function(buf) {
|
74 | busboy.write(buf);
|
75 | });
|
76 | busboy.end();
|
77 |
|
78 | process.on('exit', function() {
|
79 | assert(finishes === 1, 'busboy did not finish');
|
80 | });
|