Home > Software engineering >  Saving docx file from URL using NodeJS
Saving docx file from URL using NodeJS

Time:09-14

I would like to download a docx file content from a url to S3 using Node JS. Is there a suggested library for doing the same. I tried to download locally using something like this but it turns out the document contents are Gibberish. Is there anything I am missing here.

const axios = require("axios");
const fs = require("fs");

(async function () {
  let article;
  try {
    const httpResponse = await axios.get("https://<url>/Go_Lang.docx?raw=true", 
    {responseType: 'blob', headers : { 'Accept': "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}});
      fs.writeFileSync(“./temp.docx", Buffer.from(httpResponse.data), function (err) {
        if (err) console.log(err);
        else console.log("done");
      });
  } catch (err) {
console.log(err)
  }
})();

CodePudding user response:

Change responseType to arraybuffer, and you don't need to convert it to Buffer.

Also, .writeFileSync does not take callback, so it's writeFile

try this:

(async function() {
    let article;
    try {
        const httpResponse = await axios.get("https://<url>/Go_Lang.docx?raw=true", {
            responseType: 'arraybuffer',
            headers: {
                'Accept': "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            }
        });
        fs.writeFile("./temp.docx", httpResponse.data, function (err) {
        if (err) console.log(err);
        else console.log("done");
      });
    } catch (err) {
        console.log(err)
    }
})();
  • Related