How to Upload Files to Google Drive with Node.js

Uploading files to Google Drive using Node.js is straightforward thanks to Google's official APIs. This guide will walk you through the setup and code needed to authenticate and upload a file.

1. Set Up Your Google Cloud Project

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one.
  3. Enable the "Google Drive API" from the API & Services library.
  4. Go to "Credentials" and create an OAuth 2.0 Client ID.
  5. Download the JSON file with your credentials and save it locally (e.g., credentials.json).

2. Install Required Dependencies

npm install googleapis

3. Authorize and Obtain Access Token

Create a script called authorize.js to handle user authentication and token generation:


const fs = require('fs');
const readline = require('readline');
const { google } = require('googleapis');

const SCOPES = ['https://www.googleapis.com/auth/drive.file'];
const TOKEN_PATH = 'token.json';

fs.readFile('credentials.json', (err, content) => {
  if (err) return console.error('Error loading client secret file:', err);
  authorize(JSON.parse(content));
});

function authorize(credentials) {
  const { client_secret, client_id, redirect_uris } = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);

  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client);
    oAuth2Client.setCredentials(JSON.parse(token));
    uploadFile(oAuth2Client);
  });
}

function getAccessToken(oAuth2Client) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      uploadFile(oAuth2Client);
    });
  });
}

4. Upload a File

Add this function to upload a file to Google Drive:


function uploadFile(auth) {
  const drive = google.drive({ version: 'v3', auth });
  const fileMetadata = {
    name: 'example.txt'
  };
  const media = {
    mimeType: 'text/plain',
    body: fs.createReadStream('example.txt'),
  };
  drive.files.create({
    resource: fileMetadata,
    media: media,
    fields: 'id',
  }, (err, file) => {
    if (err) {
      console.error('Error uploading file:', err);
    } else {
      console.log('File ID:', file.data.id);
    }
  });
}

5. Run the Script

node authorize.js

The first time you run the script, it will prompt you to authorize access. After authorization, the access token will be saved, and the file will be uploaded.

Conclusion

By following these steps, you can automate file uploads to Google Drive using Node.js. Once you've set up the credentials and token, subsequent uploads require no manual intervention.

Back to top