Patrick Hund
Patrick Hund

Reputation: 20236

How to update existing file on Google Drive with the Google API Node.js client?

Im using the Google API Node.js client to manage files on Google Drive with a Node.js program.

I've succeeded in downloading a file using this library, now I want to upload an updated version of the file back to Google Drive.

The documentation explains really well how to create a new file on Google Drive:

var fileMetadata = {
  'name': 'photo.jpg'
};
var media = {
  mimeType: 'image/jpeg',
  body: fs.createReadStream('files/photo.jpg')
};
drive.files.create({
  resource: fileMetadata,
  media: media,
  fields: 'id'
}, function (err, file) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    console.log('File Id: ', file.id);
  }
});

However, I failed to find any information on how to overwrite an existing file with a new version.

Other posts on Stack Overflow like this one, as well as the Google docs, only explain how to use the Rest API directly for updating files.

I'm wondering if there is an easier way – since there is a nice API client library provided that lets me create new files, surely, it should also let me update existing ones?

Upvotes: 1

Views: 3558

Answers (1)

afenster
afenster

Reputation: 3608

To update the existing file, use drive.files.update (definition here).

drive.files.update({
  fileId: file.id,
  resource: fileMetadata,
  media: media
}, (err, file) => {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    console.log('File Id: ', file.id);
  }
});

Note that you can also use the promise interface and async/await for both drive.files.create and drive.files.update.

Upvotes: 3

Related Questions