Skip to content

Commit

Permalink
typos and readmes
Browse files Browse the repository at this point in the history
  • Loading branch information
dudewheresmycode committed Feb 5, 2018
1 parent d0074b6 commit 4bdb2ca
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,22 @@ A simple multipart/form-data parser for AWS lambda functions.
```
npm install -S lambda-multipart
```

```js
exports.handler = function(event, context, callback){
var Multipart = require('lambda-multipart');
var parser = new Multipart(event);
parser.on('file',function(file){
//file.headers['content-type']
file.pipe(fs.createWriteStream(__dirname+"/downloads/"+file.filename));
});
parser.on('finish',function(result){
//result.files (array of file streams)
//result.fields (object of field key/values)
console.log("Finished")
});
}
```

### Thanks
@hapijs for https://github.com/hapijs/pez
18 changes: 13 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,38 @@
var Pez = require('pez');
var events = require("events");
var util = require("util");

var CONTENT_TYPE_RE = /^multipart\/(?:form-data|related)(?:;|$)/i;
var CONTENT_TYPE_PARAM_RE = /;\s*([^=]+)=(?:"([^"]+)"|([^;]+))/gi;

function multipart(event, callback){
function multipart(event){
var that = this;
events.EventEmitter.call(this);
that.contentType = event.headers['content-type'];
if(!that.contentType){ that.contentType = event.headers['Content-Type']; }
const dispenser = new Pez.Dispenser({ boundary: that.getBoundry(that.contentType) });
const dispenser = new Pez.Dispenser({ boundary: that.getBoundary(that.contentType) });
that.fields = {};
that.files = [];
dispenser.on('part', (part) => {
that.files.push(part);
that.emit('file', part)
});
dispenser.on('field', (name, value) => {
that.fields[name]=value;
that.emit('field', that.fields[name])
});
dispenser.on('error',function(e){
callback(e);
that.emit('error', {error:e})
});
dispenser.on('close',function(){
callback(null, {files:that.files, fields:that.fields});
//callback(null, {files:that.files, fields:that.fields});
that.emit('finish', {files:that.files, fields:that.fields})
});
dispenser.write(event.body, event.isBase64Encoded ? "base64" : "binary");
dispenser.end();
}

multipart.prototype.getBoundry = function(contentType){
multipart.prototype.getBoundary = function(contentType){
var m = CONTENT_TYPE_RE.exec(contentType);
if (!m) {
callback(null, {statusCode: 415, body: "unsupported content-type", headers: {"Content-Type":"text/plain"}});
Expand All @@ -44,4 +50,6 @@ multipart.prototype.getBoundry = function(contentType){
return boundary;
}

util.inherits(multipart, events.EventEmitter);

module.exports = multipart;

0 comments on commit 4bdb2ca

Please sign in to comment.