I need a service to download an excel file from Amazon S3, then parse with node-xlsx
The problem is that I can\'t get xlsx to parse the file. When I try to read back
If you want use async/wait, here solution:
const AWS = require('aws-sdk');
const XLSX = require('xlsx');
AWS.config.update({
accessKeyId: AMAZON_ACCESS_KEY,
secretAccessKey: AMAZON_SECRET_ACCESS_KEY,
});
// Get buffered file from s3
function getBufferFromS3(file, callback){
const buffers = [];
const s3 = new AWS.S3();
const stream = s3.getObject({ Bucket: 'yor_buket', Key: file}).createReadStream();
stream.on('data', data => buffers.push(data));
stream.on('end', () => callback(null, Buffer.concat(buffers)));
stream.on('error', error => callback(error));
}
// promisify read stream from s3
function getBufferFromS3Promise(file) {
return new Promise((resolve, reject) => {
getBufferFromS3(file, (error, s3buffer) => {
if (error) return reject(error);
return resolve(s3buffer);
});
});
};
// create workbook from buffer
const buffer = await getBufferFromS3Promise(file);
const workbook = XLSX.read(buffer);
// If you want to send the workbook as a download to the api end point in node
const fileName = "Categories.xlsx";
res.setHeader('Content-disposition', 'attachment; filename=' + fileName);
res.setHeader('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer'});
res.send(new Buffer(wbout));