8

I have a Buffer which I know is a multipart/form-data payload, and I also know the HTTP Content-Type header in advance, which includes the boundary.

There are modules such as node-formidable which work only on http request streams, so what I'm interested in is how to parse a multipart payload synchronously?

0x8890
  • 515
  • 1
  • 4
  • 12

1 Answers1

12

Looking at the source for formidable's form.parse(), you should be able to do mimic most of what it's doing internally.

Another solution might be to use something like busboy which gives you a plain old parser stream to write to, so you might end up with something like:

var Busboy = require('busboy');
var bb = new Busboy({ headers: { 'content-type': '....' } });

bb.on('file', function(fieldname, file, filename, encoding, mimetype) {
  console.log('File [%s]: filename=%j; encoding=%j; mimetype=%j',
              fieldname, filename, encoding, mimetype);
  file.on('data', function(data) {
    console.log('File [%s] got %d bytes', fieldname, data.length);
  }).on('end', function() {
    console.log('File [%s] Finished', fieldname);
  });
}).on('field', function(fieldname, val) {
  console.log('Field [%s]: value: %j', fieldname, val);
}).on('finish', function() {
  console.log('Done parsing form!');
});

bb.end(someBuffer);
Martin Booth
  • 8,485
  • 31
  • 31
mscdex
  • 104,356
  • 15
  • 192
  • 153
  • Using this i get a "done parsing form" but no "fields" or "data" is parsed. I'm using a buffer provided by https://github.com/CollectionFS/Meteor-http-methods and the POST is being sent by mailgun " Sample POST" WebHook test. any ideas? – kroe Nov 15 '16 at 06:33