JavaGeek
JavaGeek

Reputation: 1539

How to read and save pdf file from response in Node JS client

I have created a Node JS server that pushes the PDF to client as below

app.post("/home", function(req, res, next) {

    // to download the file automatically
    /*
    var file = fs.createReadStream('E:\\test\\conversion\\310-output.pdf');
    var stat = fs.statSync('E:\\test\\conversion\\310-output.pdf');
    res.setHeader('Content-Length', stat.size);
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=output.pdf');
    file.pipe(res);
    */
    // To Stream file to browser

    var data =fs.readFileSync('E:\\test\\conversion\\310-output.pdf');
    res.contentType("application/pdf");
    res.send(data);

    });

In client script, i am trying to call above post command and want to fetch the pdf and save it locally from response. Not sure how to do it. Below is client script. In browser, i was able to see the PDF but i need to access it through client script

var request = require('request');

request.post(
    'http://localhost:3000/home',
    {},
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(" Response :: "+response);
           // console.log(" Body :: "+body);
        }
    }
);

Upvotes: 1

Views: 7955

Answers (2)

subrahmanya bhat
subrahmanya bhat

Reputation: 598

To recieve your pdf response in proper format request "responseType": 'arraybuffer', and "responseEncoding": 'binary' while calling the api

  const config = {
      baseURL: "<your base url>",
      url: "<api endpoint>",
      headers: {},
      method: "<method>",
      responseType: "arraybuffer",
      responseEncoding: "binary"
      
    }
    
    let response = await axios(config)
    
    //response.data will be binary encoded buffer Array of pdf data

    //*To convert to base64*
    var base64 = response.data.toString("base64")
    
    
    //to convert to binary
    var binary = response.data.toString("binary")
    
    //to write to file
    fs.writeFileSync(`${name}.pdf`, response.data, 'binary');

Upvotes: 2

hoangdv
hoangdv

Reputation: 16157

To download a file by request lib, we will to many ways to do that (I think so!)

Below is a simple way: Create a pipe stream from request response, then save data from stream to a file with a write stream

const request = require('request');
const fs = require('fs');

const req = request.post(
  'http://localhost:3000/home',
  {},
);


req.on('response', function (res) {
  res.pipe(fs.createWriteStream('./filename_to_save.pdf'));
});

Upvotes: 1

Related Questions