DEV Community

Cover image for Upload Files on Drive With Node.js
Arjun Tripathi
Arjun Tripathi

Posted on

Upload Files on Drive With Node.js

In situations where storage limitations become a concern, exploring alternative solutions becomes essential. Suppose you're utilizing platforms like GitHub or Versal for hosting frontend applications, which offer restricted storage space, typically around 2GB. In such scenarios, leveraging Google Drive for storing files can be a viable option.

By integrating Google Drive with your Node.js applications, you can harness the robust storage capabilities of Google Cloud. This documentation aims to provide a concise guide on utilizing Google Drive in conjunction with Node.js to manage files efficiently.

Prerequisites

Before embarking on the integration process, ensure you have the following prerequisites in place:

  1. A Google account with access to the Google Cloud Console.
  2. Node.js installed on your local machine.
  3. NPM (Node Package Manager) installed.

Step 1: Set Up Google Cloud Console and Enable Google Drive API

  1. Go to the Google Cloud Console.
  2. Create a new project.
  3. Navigate to "APIs & Services" > "Library". Image description
  4. Search for "Google Drive API" and enable it. Image description

Step 2: Obtain Service Account Credentials

  1. Navigate to "APIs & Services" > "Credentials". Image description
  2. Create a new Service Account. Image description
  3. Download the JSON file with the credentials. Image description

Step 3: Install Necessary Packages

Install the required packages using NPM. This includes the 'googleapis' package, which facilitates interaction with Google APIs.

npm install googleapis
Enter fullscreen mode Exit fullscreen mode

Step 4: Implement File Management Functions
Utilize the provided code snippets to implement various file management functionalities, including:

  • Listing available files in Google Drive.
  • Uploading files to Google Drive.
  • Updating existing files in Google Drive.
  • Deleting files from Google Drive.
  • for that you should use folder_id and make it public and editable Image description Image description Image description

Step 5: Start the project

Execute the Node.js application to perform file management operations on Google Drive. Ensure to replace placeholders such as 'FOLDER_ID_HERE' with relevant IDs and file paths. For geting folder id of drive folder we do this.
Image description

Let' Code

first we import all necessary libararies

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

// Load API credentials from JSON file
const apikeys = require('FOLDER_ID_HERE');  // Replace 'FOLDER_ID_HERE' with the downloaded api file path
Enter fullscreen mode Exit fullscreen mode

Function to authorize and get access to Google Drive API

// Define the scope for Google Drive API
const SCOPES = ['https://www.googleapis.com/auth/drive'];

// Function to authorize and get access to Google Drive API
async function authorize() {
    const auth = new google.auth.JWT(
        apikeys.client_email,
        null,
        apikeys.private_key,
        SCOPES
    );

    try {
        await auth.authorize();
        return auth;
    } catch (error) {
        throw new Error(`Error authorizing Google Drive API: ${error.message}`);
    }
}
Enter fullscreen mode Exit fullscreen mode

Write a function for get all available file on that drive folder

// Function to list available files in Google Drive
async function listFiles(auth) {
    const drive = google.drive({ version: 'v3', auth });

    try {
        const response = await drive.files.list({
            pageSize: 10,
            fields: 'nextPageToken, files(id, name)',
        });

        const files = response.data.files;
        if (files.length) {
            console.log('Available files:');
            files.forEach(file => {
                console.log(`${file.name} (${file.id})`);
            });
        } else {
            console.log('No files found.');
        }
    } catch (error) {
        throw new Error(`Error listing files in Google Drive: ${error.message}`);
    }
}
Enter fullscreen mode Exit fullscreen mode

Write a function to upload file on drive folder

// Function to upload a file to Google Drive
async function uploadFile(auth, filePath, folderId) {
    const drive = google.drive({ version: 'v3', auth });

    const fileMetadata = {
        name: filePath.split('/').pop(), // Extract file name from path
        parents: [folderId] // Folder ID to upload the file into
    };

    const media = {
        mimeType: 'application/octet-stream',
        body: fs.createReadStream(filePath) // Readable stream for file upload
    };

    try {
        const response = await drive.files.create({
            resource: fileMetadata,
            media: media,
            fields: 'id'
        });

        console.log('File uploaded successfully. File ID:', response.data.id);
        return response.data;
    } catch (error) {
        throw new Error(`Error uploading file to Google Drive: ${error.message}`);
    }
}

Enter fullscreen mode Exit fullscreen mode

Function to delete file to folder

// Function to delete a file from Google Drive
async function deleteFile(auth, fileId) {
    const drive = google.drive({ version: 'v3', auth });

    try {
        await drive.files.delete({
            fileId: fileId
        });

        console.log('File deleted successfully.');
    } catch (error) {
        throw new Error(`Error deleting file from Google Drive: ${error.message}`);
    }
}
Enter fullscreen mode Exit fullscreen mode

Function to update file of drive folder

// Function to update a file in Google Drive
async function updateFile(auth, fileId, filePath) {
    const drive = google.drive({ version: 'v3', auth });

    const fileMetadata = {
        name: filePath.split('/').pop() // Extract file name from path
    };

    const media = {
        mimeType: 'application/octet-stream',
        body: fs.createReadStream(filePath) // Readable stream for file update
    };

    try {
        const response = await drive.files.update({
            fileId: fileId,
            resource: fileMetadata,
            media: media
        });

        console.log('File updated successfully.');
    } catch (error) {
        throw new Error(`Error updating file in Google Drive: ${error.message}`);
    }
}
Enter fullscreen mode Exit fullscreen mode

How to call all function

// Main function to demonstrate file operations
async function main() {
    try {
        const authClient = await authorize();

        // List available files
        console.log('Available files:');
        await listFiles(authClient);

        // Upload a file
        const uploadedFile = await uploadFile(authClient, 'test.txt', 'FOLDER_ID_HERE'); // Replace 'FOLDER_ID_HERE' with the desired folder ID
        const fileId = uploadedFile.id;

        // Update the uploaded file
        await updateFile(authClient, fileId, 'updated_test.txt');

        // Delete the uploaded file
        await deleteFile(authClient, '1kWgn2c_yfXWDnT4DC6ZlUJEG37w79JxA');
    } catch (error) {
        console.error(error);
    }
}

// Call the main function to start the process
main();
Enter fullscreen mode Exit fullscreen mode

After doing all performance we can easily asses drive to upload folder.

Top comments (0)