UNPKG

2.64 kBJavaScriptView Raw
1var Busboy = require('..');
2
3var path = require('path');
4var inspect = require('util').inspect;
5var assert = require('assert');
6
7function 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}
12function 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
22var BOUNDARY = 'u2KxIV5yF1y+xUspOQCCZopaVgeV6Jxihv35XQJmuTx8X3sh';
23var 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];
31var busboy = new Busboy({
32 headers: {
33 'content-type': 'multipart/form-data; boundary=' + BOUNDARY
34 }
35});
36var finishes = 0;
37var results = [];
38var 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
44busboy.on('field', function(key, val, keyTrunc, valTrunc, encoding, contype) {
45 results.push(['field', key, val, keyTrunc, valTrunc, encoding, contype]);
46});
47busboy.on('file', function(fieldname, stream, filename, encoding, mimeType) {
48 results.push(['file', fieldname, filename, encoding, mimeType]);
49 // Simulate a pipe where the destination is pausing (perhaps due to waiting
50 // for file system write to finish)
51 setTimeout(function() {
52 stream.resume();
53 }, 10);
54});
55busboy.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
73reqChunks.forEach(function(buf) {
74 busboy.write(buf);
75});
76busboy.end();
77
78process.on('exit', function() {
79 assert(finishes === 1, 'busboy did not finish');
80});