You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.6 KiB

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