Home > database >  nodejs- Downloading pdf, error in converting using fs (file wont open)
nodejs- Downloading pdf, error in converting using fs (file wont open)

Time:12-16

I make an api call , and receive a response.

if i write the resposne to console

console.log(resp2.data)

i see h�l�A♂�@►�ῲ7����§�t)A0輺#n�‼�J��[#:u{☼���~�8K� �M�䖒▬����↨�8♀0����S��Z♦�h∟♂i�-♫�♂◄�0....

I then try to convert it to pdf using the below, which downloads the file (a pdf) but i cannot then open the file.

(We can't open this file Something went wrong.)

         // load your response data into a Buffer
         let buffer = Buffer.from(resp2.data)
       
         // open the file in writing mode
         fs.open(filePath  'feed3'  ".pdf", 'w', function(err, fd) {  
           if (err) {
               throw 'could not open file: '   err;
           }
       
           // write the contents of the buffer
           fs.write(fd, buffer, 0, buffer.length, null, function(err) {
             if (err) {
               throw 'error writing file: '   err;
             }
             fs.close(fd, function() {
                 console.log('file written successfully');
             });
           });
         });
     

what am i doing wrong? also is that base64, or how do you refer to those characters?

***edit, in my call i have headers as


     try {
            const resp2 = await axios.get(url2,
            {headers:{
              'accept': 'application/pdf',
              'Authorization': "Bearer "   myAccessToken
            }
            });

if i use the following

  

      fs.writeFile(filePath  'feed'  ".txt", resp2.data, function 
      (err){
                          if (err) throw err;
                              console.log('It\'s saved!');
                          });
    
            } catch (err) {
              console.error(err);
            }
    
    
          } catch (err) {
            console.error(err);
          }
          };
        

(which is as text i know) the file is written with


    %PDF-1.6
    %����
    4 0 obj
    <<
    /ProcSet [/PDF /ImageC /Text]
    /Font
    <<

up top.

and when i change to .pdf, and open the pdf it is blank.

i have tried writeFileSync, but still no resolution.

****update again am trying

            fs.writeFile(filePath  'feed'  ".pdf", buf, didit() )

    function didit(){

      console.log("done")
    }

but still not getting it

CodePudding user response:

  const filePath = './data/';
  let url2 = 'example.com';
  axios
  .get(url2, {
      headers: {'Authorization': "Bearer "   myAccessToken},
      responseType: 'stream', // had to add this one here
  })
  .then(response => {
    response.data.pipe(fs.createWriteStream(filePath   "good.pdf"))
  })
  .catch(error => console.log(error));
   }
  • Related