Created
January 27, 2016 21:07
-
-
Save eperedo/9d7513227f9726e75370 to your computer and use it in GitHub Desktop.
Read xls, xlsx and csv files and return json object (inside a hapijs handler)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
handler: function (request, reply) { | |
const path = require('path'); | |
const response = reply('success').hold(); | |
const fileExtension = path.extname(request.payload.file.filename); | |
if (fileExtension === '.csv') { | |
const csv = require('csv-to-json'); | |
csv.parse( { filename: request.payload.file.path }, (err, json) => { | |
response.source = json; | |
return response.send(); | |
}); | |
} | |
else if (fileExtension === '.xls' || fileExtension === '.xlsx') { | |
const xls = require('xlsx'); | |
const workbook = xls.readFile(request.payload.file.path); | |
response.source = xls.utils.sheet_to_json(workbook.Sheets[Object.keys(workbook.Sheets)[0]]); | |
return response.send(); | |
} | |
else { | |
response.statusCode = 500; | |
return response.send(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Packages:
npm install csv-to-json
npm install xlsx