Skip to content

Instantly share code, notes, and snippets.

@trulymittal
Last active November 6, 2024 17:53
Show Gist options
  • Save trulymittal/fd9c4bfd1f22fb9c62847a351dcbf0a5 to your computer and use it in GitHub Desktop.
Save trulymittal/fd9c4bfd1f22fb9c62847a351dcbf0a5 to your computer and use it in GitHub Desktop.
Gist to demonstrate Google Drive API using NodeJs
/*
Google Drive API:
Demonstration to:
1. upload
2. delete
3. create public URL of a file.
required npm package: googleapis
*/
const { google } = require('googleapis');
const path = require('path');
const fs = require('fs');
const CLIENT_ID = 'YOUR CLIENT ID';
const CLIENT_SECRET = 'YOUR CLIENT SECRET';
const REDIRECT_URI = 'https://developers.google.com/oauthplayground';
const REFRESH_TOKEN = 'YOUR REFRESH TOKEN GENERATED FROM oauthplayground';
const oauth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URI
);
oauth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });
const drive = google.drive({
version: 'v3',
auth: oauth2Client,
});
/*
filepath which needs to be uploaded
Note: Assumes example.jpg file is in root directory,
though this can be any filePath
*/
const filePath = path.join(__dirname, 'example.jpg');
async function uploadFile() {
try {
const response = await drive.files.create({
requestBody: {
name: 'example.jpg', //This can be name of your choice
mimeType: 'image/jpg',
},
media: {
mimeType: 'image/jpg',
body: fs.createReadStream(filePath),
},
});
console.log(response.data);
} catch (error) {
console.log(error.message);
}
}
// uploadFile();
async function deleteFile() {
try {
const response = await drive.files.delete({
fileId: 'YOUR FILE ID',
});
console.log(response.data, response.status);
} catch (error) {
console.log(error.message);
}
}
// deleteFile();
async function generatePublicUrl() {
try {
const fileId = 'YOUR FILE ID';
await drive.permissions.create({
fileId: fileId,
requestBody: {
role: 'reader',
type: 'anyone',
},
});
/*
webViewLink: View the file in browser
webContentLink: Direct download link
*/
const result = await drive.files.get({
fileId: fileId,
fields: 'webViewLink, webContentLink',
});
console.log(result.data);
} catch (error) {
console.log(error.message);
}
}
// generatePublicUrl();
@shelomito12
Copy link

shelomito12 commented Dec 15, 2022

Thanks! this sample is very useful for a quick demo, in particular the upload function.

For those (like me) who rather want to use service account instead of access token, then replace this:

const CLIENT_ID = 'YOUR CLIENT ID';
const CLIENT_SECRET = 'YOUR CLIENT SECRET';
const REDIRECT_URI = 'https://developers.google.com/oauthplayground';

const REFRESH_TOKEN = 'YOUR REFRESH TOKEN GENERATED FROM oauthplayground';

const oauth2Client = new google.auth.OAuth2(
  CLIENT_ID,
  CLIENT_SECRET,
  REDIRECT_URI
);

oauth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });

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

with this:

  const KEYFILEPATH = path.join(`${__dirname}/../service-account.json`);
  const SCOPES = ['https://www.googleapis.com/auth/drive'];

  const auth = new google.auth.GoogleAuth({
    keyFile: KEYFILEPATH,
    scopes: SCOPES,
  });

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

@shihab-uddin-shakil
Copy link

shihab-uddin-shakil commented Apr 12, 2023

mimeType: 'image/jpg',
i want to upload all type of file..how i will write syntax.
i tried this mimeType: / work but preview can't work.
thanks lot.

@pks9918705
Copy link

pks9918705 commented Oct 6, 2023

mimeType: 'image/jpg', i want to upload all type of file..how i will write syntax. i tried this mimeType: / work but preview can't work. thanks lot.
bro use ,

` async function uploadFile() {
try {
const response = await drive.files.create({
requestBody: {
name: 'Jai Shree Ram- PDF', //This can be name of your choice
// mimeType: 'image/jpg',
mimeType: 'application/octet-stream'
},
media: {
// mimeType: 'image/jpg',
body: fs.createReadStream(filePath),
},
});

console.log("Uploaded successfully",response.data);

} catch (error) {
console.log(error.message);
}
}

uploadFile(); `

@bek-shoyatbek
Copy link

Thanks for it 👍 but I have a question that instead of fs.readStream , can we use buffer directly from multer file in incoming request ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment