How to save pdf in proper encoding via nodejs

a 夏天 提交于 2020-01-11 06:28:06

问题


So I'm trying to download a pdf file from a website with my script but the problem is that the file gets broken in the process and I'm pretty sure it's because of wrong encoding being used.

I'm using request lib for downloading the file and I've set the Content-type to application-pdf

My code is pretty simple:4

var fs = require('fs');
var request = require("request");


request({uri: 'xxxxxxxxxxxxxx.pdf', headers: { 'Content-type' : 'applcation/pdf' }} , function (error, response, body) {
  if (!error && response.statusCode == 200) {
    fs.writeFileSync("10111.pdf", body);
  }
})

Where do I need to specify the encoding used for this to work?

I tried opening the pdf that I get by normal saving and SublimeText3 encodinghelper says it's in Windows-something while the one I downloaded is in utf8.

I've gone through the nodejs buffer and fs files and they do not supprt encodings like windows-asd, only the general ones like 'utf8' and 'binary'.

Should I maybe use a different method for obtaining the file?


回答1:


I know its very late but i seen your question today so i am answering it so that other can get help from this. You can add the encoding when you are trying to write the file i.e-:

fs.writeFileSync("10111.pdf", body,'binary');

As i set encoding format as binary here you can use which is right encoding format according to your requirenment if you are trying to download a pdf that you can set encoding as null.

Hope this would help




回答2:


In order to write the PDF properly, you may have to encode the steam in base64. There is a great answer available here

You can check the documentation for writeFileSync here

Here is how the code should look like:

var fs = require('fs');
var request = require("request");


request({uri: 'xxxxxxxxxxxxxx.pdf', headers: { 'Content-type' : 'applcation/pdf' }} , function (error, response, body) {
  if (!error && response.statusCode == 200) {
    fs.writeFileSync("10111.pdf", body,
      {
        encoding :'base64',
      }
    );
  }
})


来源:https://stackoverflow.com/questions/31040014/how-to-save-pdf-in-proper-encoding-via-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!