From 4bdb2cac2e3a4746408e87fd5ed1f7436b9fa820 Mon Sep 17 00:00:00 2001 From: Brian Robinson Date: Sun, 4 Feb 2018 23:41:24 -0800 Subject: [PATCH] typos and readmes --- README.md | 19 +++++++++++++++++++ index.js | 18 +++++++++++++----- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 231e02a..39ba4e6 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/index.js b/index.js index 7479e61..6808b47 100644 --- a/index.js +++ b/index.js @@ -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"}}); @@ -44,4 +50,6 @@ multipart.prototype.getBoundry = function(contentType){ return boundary; } +util.inherits(multipart, events.EventEmitter); + module.exports = multipart;