Skip to content

Instantly share code, notes, and snippets.

@MWaris97
Last active May 14, 2024 11:47
Show Gist options
  • Select an option

  • Save MWaris97/2601a01f9cf7b871a1b3ea2d5e152e1f to your computer and use it in GitHub Desktop.

Select an option

Save MWaris97/2601a01f9cf7b871a1b3ea2d5e152e1f to your computer and use it in GitHub Desktop.
Code for uploading files to google drive with service account using Nodejs
const createReadStream = require('fs').createReadStream;
const path = require('path');
const process = require('process');
const { google } = require('googleapis');
// Downloaded from while creating credentials of service account
const pkey = require('./pk.json');
const SCOPES = ['https://www.googleapis.com/auth/drive.file'];
/**
* Authorize with service account and get jwt client
*
*/
async function authorize() {
const jwtClient = new google.auth.JWT(
pkey.client_email,
null,
pkey.private_key,
SCOPES
)
await jwtClient.authorize();
return jwtClient;
}
/**
* Create a new file on google drive.
* @param {OAuth2Client} authClient An authorized OAuth2 client.
*/
async function uploadFile(authClient) {
const drive = google.drive({ version: 'v3', auth: authClient });
const file = await drive.files.create({
media: {
body: createReadStream('filename')
},
fields: 'id',
requestBody: {
name: path.basename('filename'),
},
});
console.log(file.data.id)
}
//authorize().then(uploadFile).catch(console.error);
@emmanuelekopimo
Copy link

The listing worked and returned all the files I've uploaded with the IDs. But I can't still see the files in my Drive. The storage info on my Drive shows that there are some files. Although I can't see them. It's not much of a problem because I can still get the files using the file ID. Thanks

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