DEV Community

Kamal Hossain
Kamal Hossain

Posted on

Download and Delete via Google Drive API

Last time I spent my times in followings:

  • Create a node.js server by using express.js
  • Get authentication for Google Drive
  • Upload an image file to Google Drive from node.js server

Today I am going to show how to download an image file from google drive, by using google drive API in node.js server and also how to delete an image file.

Again if you don't want to follow the tutorial download the Source code


Download file via google drive API in node.js

We are not going to create a new node.js server or also not going to get new authentication from google. We are going to use the server that we have used last time. So, in the server.js file let's add another function to receive a GET request to download an image from google drive to the node.js server.

// ...

// Route for downloading an image/file
app.get('/downloadAFile', (req, res) => {
  var dir = `./downloads`; // directory from where node.js will look for downloaded file from google drive

  var fileId = '13_Iq3ImCLQqBStDQ9ottLIJwxwlXkQpa'; // Desired file id to download from  google drive

  var dest = fs.createWriteStream('./downloads/kamal-hossain.jpg'); // file path where google drive function will save the file

  const drive = google.drive({ version: 'v3', auth }); // Authenticating drive API

  let progress = 0; // This will contain the download progress amount

  // Uploading Single image to drive
  drive.files
    .get({ fileId, alt: 'media' }, { responseType: 'stream' })
    .then((driveResponse) => {
      driveResponse.data
        .on('end', () => {
          console.log('\nDone downloading file.');
          const file = `${dir}/kamal-hossain.jpg`; // file path from where node.js will send file to the requested user
          res.download(file); // Set disposition and send it.
        })
        .on('error', (err) => {
          console.error('Error downloading file.');
        })
        .on('data', (d) => {
          progress += d.length;
          if (process.stdout.isTTY) {
            process.stdout.clearLine();
            process.stdout.cursorTo(0);
            process.stdout.write(`Downloaded ${progress} bytes`);
          }
        })
        .pipe(dest);
    })
    .catch((err) => console.log(err));
});
Enter fullscreen mode Exit fullscreen mode

Let's go through the code as fast as possible.

In our express app, we are defining a get request as downloadAFile. This function will set the directory to download the file from google drive, and another directory to serve the file to the requested user. In our case both directory is the same.

We are going to download the file in our server via drive.files.get(). In there we are going to pass the desired file id to download. Rember the id that we got when last time we have uploaded a file to google drive. Also we are going to set the response time as stream, so probably we are going to get the file chunk by chunk.

So, in the above method, we are going to chain the then() in where we going to handle the response data from google.

Again in the response, we are chaining some .on() to handle the response in different stages.

First, we are adding the end stage, to tell the server what to do when the file is downloaded to our server from google drive. In our case, we are going to send the file to the requesting user from our server.

After that we are adding the error, to check if anything suspicious happens during download from google drive.

In our last .on() we are adding data to show the downloaded amount of file size in our console. We are showing the amount in bytes.

Lastly by chaining .pipe() where we are passing the destination of the folder where the google drive function should save the requested file.


Delete file via google drive api in node.js

The process is very simple.

// ...

// Route for downloading an image/file
app.delete('/deleteAFile', (req, res) => {
  var fileId = '1vuZs3N8qnevNEETCKnZQ5js0HOCpGTxs'; // Desired file id to download from  google drive

  const drive = google.drive({ version: 'v3', auth }); // Authenticating drive API

  // Deleting the image from Drive
  drive.files
    .delete({
      fileId: fileId,
    })
    .then(
      async function (response) {
        res.status(204).json({ status: 'success' });
      },
      function (err) {
        return res
          .status(400)
          .json({ errors: [{ msg: 'Deletion Failed for some reason' }] });
      }
    );
});
Enter fullscreen mode Exit fullscreen mode

Here we are using drive.files.delete() function to delete the file. We are just passing the unique file id as an argument.

Then we are handling the response via .then() and passing them to the user.


For testing both of the requests we are using postman. If you using the same, don't forget to switch between GET and DELETE for these two requests.

Top comments (0)