3

I am trying to convert a Word doc into a Google doc using the API via nodejs. The word docs are already in a folder and I just want to convert them into google docs. I am using v3.

The v3 docs say that in order to convert a file using copy you need to replace the convert parameter with the mimeType in the resource body.

I can't work out how to do that?

function listFiles(auth) {
  const drive = google.drive({version: 'v3', auth});
  drive.files.list({
    q: "mimeType = 'application/msword'",
    pageSize: 100,
    fields: 'nextPageToken, files(id, name)',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const files = res.data.files;
    if (files.length) {
      console.log('Files:');
      files.map((file) => {
        console.log(`${file.name} (${file.id})`);
        drive.files.copy({
          fileId: file.id,
          'name' : 'Updated File Name',
          'mimeType' : 'application/vnd.google-apps.document'
        })
      });
    } else {
      console.log('No files found.');
    }
  });
}

Not sure that I am quite understanding how to reference the resource body. Would be grateful for a steer?

1 Answers1

4
  • You want to convert Microsoft Word (doc files) to Google Document using the method of files.copy in Drive API v3.
  • You want to achieve this using googleapis with Node.js.
  • You have already been able to get and put files for Google Drive using Drive API.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification points:

  • I think that drive.files.list() works in your script.
  • I think that drive.files.copy() has a modification part.
    • Please include name and mimeType in requestBody or resource.
    • In this case, it uses callback function for retrieving error message.

Modified script:

From:
drive.files.copy({
  fileId: file.id,
  'name' : 'Updated File Name',
  'mimeType' : 'application/vnd.google-apps.document'
})
To:
drive.files.copy(
  {
    fileId: file.id,
    requestBody: {  // You can also use "resource" instead of "requestBody".
      name: file.name,
      mimeType: "application/vnd.google-apps.document"
    }
  },
  (err, res) => {
    if (err) return console.log("The API returned an error: " + err);
    console.log(res.data);  // If you need, you can see the information of copied file.
  }
);
  • In this case, the filename of the DOC file is used by removing the extension. And the copied file is put to the same folder with the DOC file.

Note:

  • In this modified script, it suppose that the scopes you set can be used for using drive.files.copy(). If an error related to the scopes occurs, please add https://www.googleapis.com/auth/drive to the scopes.

References:

If I misunderstood your question and this was not the direction you want, I apologize.

Tanaike
  • 181,128
  • 11
  • 97
  • 165