Skip to content

Instantly share code, notes, and snippets.

@lastday154
Created June 6, 2018 02:14
Show Gist options
  • Save lastday154/2679ccf617bea1c9a71e1447302d2039 to your computer and use it in GitHub Desktop.
Save lastday154/2679ccf617bea1c9a71e1447302d2039 to your computer and use it in GitHub Desktop.
busboy parse multi-part form lambda
'use strict';
const csv = require('csvtojson');
const stringToRow = (csvStr) => new Promise((resolve, reject) => {
csv({
noheader: true,
output: 'csv'
})
.fromString(csvStr)
.then((csvRow) => {
resolve(csvRow);
})
.catch((error) => {
reject(`Parse error: ${error}`);
});
});
module.exports = {
stringToRow
};
'use strict';
const Busboy = require('busboy');
const getContentType = (event) => {
const contentType = event.headers['content-type'];
if (!contentType) {
return event.headers['Content-Type'];
}
return contentType;
};
const parser = (event) => new Promise((resolve, reject) => {
const busboy = new Busboy({
headers: {
'content-type': getContentType(event),
}
});
const result = {};
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
file.on('data', (data) => {
result.file = data;
});
file.on('end', () => {
result.filename = filename;
result.contentType = mimetype;
});
});
busboy.on('field', (fieldname, value) => {
result[fieldname] = value;
});
busboy.on('error', (error) => reject(`Parse error: ${error}`));
busboy.on('finish', () => {
event.body = result;
resolve(event);
});
busboy.write(event.body, event.isBase64Encoded ? 'base64' : 'binary');
busboy.end();
});
module.exports = {
parser
};
// how to use:
const { body } = await parser(event);
const data = body.file.toString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment