TechChain
TechChain

Reputation: 8944

Unable to read octet stream response in node js?

I have an API that returns response as 'octet-stream'. Here is swagger defination for the same.

responses: {
  '200': {
    description: 'Will return the pdf for an invoice',
      content: {
      'application/octet-stream': {
        schema: '',
      },
    },
  },
}

From postman and swagger ui i am able to save the response as a PDF File. but with node i am not able to write the pdf file.

Below is code for node js to call the API.

var fs = require('fs');
var request = require('request');
let headers = {
  'Content-Type': 'application/json',
  'accept': "application/octet-stream",
}
let body = {
  "invoiceId": "343",
  "slCompId": 243,
  "platfromCompId": "4620816365013235830"
}

request.post({
  headers,
  url: 'http://localhost:3001/invoice/',
  json: body
},
  function (error, response, body) {
    console.log(response);
    console.log("response");
    fs.writeFile('a.pdf', response.body, 'binary')
  });

EDIT:

The PDF file which is written is corrupted. There is nothing inside the file and PDF viewer gives me error in opening the file.

Upvotes: 0

Views: 8885

Answers (1)

TechChain
TechChain

Reputation: 8944

I have found a solution to this problem. I tried hitting the API with superagent with buffer as true.

async function getData() {
try  {
  var fs = require('fs');
  let res = await superagent
  .get('https://localhost:3000/invoice')
  .set("Content-Type", "application/json")
  .set("accept", "application/octet-stream")
  .buffer(true).disableTLSCerts()
  console.log(res)
  fs.writeFile('a.pdf',res.body)
 }

catch(error) {
  console.log("error " + error)
}
}

Upvotes: 3

Related Questions