TheMan68
TheMan68

Reputation: 1469

Problems exporting document to local google apis

I'm having some real trouble downloading files from google drive via googleapis node.

This is my current code that I've got working to

drive.files.export(
    {
        auth: this.jwtToken,
        fileId: fileId,
        mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    }, 
    async function (err, file, response) 
    {
        console.log(file.data);
    }
)

Out put is text like the following:

�0$Ҡċ�E��4���G��[�V�%�;]�4,횕9�M������;

�� o���(�* S��Ca�VJ�e\a���}8x%3�a֩�3��L��4f�4�:�<H2�`�ʗ� ���-6�g�����[K������[���M��&zD1��S�����@�ǽ5�b��ظ��w�~���#-�P\ϲ�lt�!Q��M�"�

But when I use the code from the google example as seen here: https://developers.google.com/drive/api/v3/manage-downloads

I get the following errors:

TypeError: drive.files.export(...).on is not a function

And when I try to save the string from my method then I get a corrupt file when I try to open it.

What am I doing wrong?

Upvotes: 2

Views: 151

Answers (1)

Tanaike
Tanaike

Reputation: 201428

I believe your goal as follows.

  • You want to export Google Document as Microsoft DOCX format using googleapis for Node.js.
  • You have already been able to get the file content using Drive API.

Issue:

Unfortunately, I think that the script of Node.js in the official document might not be updated. By this, an error occurs. When you are using the latest version of googleapis for Node.js (Now it's [email protected].), how about the following sample script?

Sample script:

const fileId = "###";  // file ID of Google Document.
const dest = fs.createWriteStream("###");  // Filename. Google Document is saved as the DOCX format to this file.

drive.files.export(
  {
    auth: this.jwtToken,,
    fileId: fileId,
    mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  },
  { responseType: "stream" },
  function (err, response) {
    if (err) {
      console.log(err);
      return;
    }
    response.data
      .on("end", function () {
        console.log("Done.");
      })
      .on("error", function (err) {
        console.log("Error during download", err);
        return process.exit();
      })
      .pipe(dest);
  }
);

Note:

  • In this answer, it supposes that you are using the latest version of googleapis for Node.js. In the current stage, it's [email protected]. Please be careful this.
  • When you want to download the file except for Google Docs file (Document, Spreadsheet, Slides and so on), please use the get method instead of the export method.

Reference:

Upvotes: 3

Related Questions