Home > OS >  Read a xlsx file without saving, which is coming from external api called from my server in nodejs
Read a xlsx file without saving, which is coming from external api called from my server in nodejs

Time:01-10

const https = require('https');
var postData = JSON.stringify({
    'msg' : 'Hello World!'
});
let url;
url = "someurl2228.com";//dummy/random url (have removed actual url)
var options = {
  hostname: url,
  path: '/file/download/b8d61eff5314ac1ac982e5dbb9630f83',
  method: 'GET',
  headers: {myheader:"somedata"}
};
var req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);
  res.on('data', (d) => {
    process.stdout.write(d);
  });
  res.on('end',()=>{
    console.log('********************END********');
  });});
req.on('error', (e) => {
  console.error(e);});
req.write(postData);
req.end();

I have removed actual urls. that is some just random url in my code above.

From my code I am using https module to call a external rest api which in response sends me a xlsx file. I want to read the file (without saving will be great).

Now, when I use Postman's Send button to call that external api I receive a unicode chracters in respose tab. enter image description here But when I use Postman's Send and Download button to call that external api I can get the xlsx file to save. enter image description here

Now, I am able to replicate same unicode as in I am receiving with Postman's Send button in my NodeJS code using https module but don't know what to do next. enter image description here

I want to read the xlsx file's data for further task.

Want to read the xlsx file's data without saving it to do further task.

Also Adding a snippet of my excel enter image description here

CodePudding user response:

You could collect the result as a buffer and then pass the result to the XLSX's .read method (which will then read it in memory).

Try this:

var req = http.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);
  
  // store buffer here
  let chunks = [];

  res.on('data', (d) => {
    chunks.push(d);
  });
  res.on('end', () => {
    console.log('********************END********');

    // feed buffer to `.read` method
    const workbook = require('xlsx').read(chunks, {type: 'buffer'});

    console.log('No more data in response.\nDo something with the workbook:\n\n', workbook);
  });
});
  • Related