sheetjs_sheetjs/demos/function/AzureHTTPTrigger/index.js
Garrett Luu 0c7e809e9c
[ci skip] Fixed functions demos (#2025)
* Added test for CRLF newlines

* Initialized firebase functions app

* Updated gitignore

* Implemented csv file conversion

* CSV conversion

* Modified README to include firebase

* Added init-azure script to makefile

* Updated Azure demo

* Updated README
2020-06-25 12:30:56 -07:00

45 lines
1.3 KiB
JavaScript

/* xlsx.js (C) 2013-present SheetJS -- http://sheetjs.com */
/* eslint-env node */
// base64 sheetjs.xlsb | curl -F "data=@-;filename=test.xlsb" http://localhost:7262/api/AzureHTTPTrigger
const XLSX = require('xlsx');
const formidable = require('formidable');
const Readable = require('stream').Readable;
var fs = require('fs');
/* formidable expects the request object to be a stream */
const streamify = (req) => {
if(typeof req.on !== 'undefined') return req;
const s = new Readable();
s._read = ()=>{};
s.push(new Buffer(req.body));
s.push(null);
Object.assign(s, req);
return s;
};
module.exports = (context, req) => {
const form = new formidable.IncomingForm();
form.parse(streamify(req), (err, fields, files) => {
/* grab the first file */
var f = Object.values(files)[0];
if(!f) {
context.res = { status: 400, body: "Must submit a file for processing!" };
} else {
/* file is stored in a temp directory, so we can point to that and read it */
const wb = XLSX.read(f.path, {type:"file"});
/* convert to specified output type -- default CSV */
const ext = (fields.bookType || "csv").toLowerCase();
const out = XLSX.write(wb, {type:"string", bookType:ext});
context.res = {
status: 200,
headers: { "Content-Disposition": `attachment; filename="download.${ext}";` },
body: out
};
}
context.done();
});
};