Google Drive authentication and file manipulation
Activate Google Drive API in Google Console https://developers.google.com/drive/api/quickstart/nodejs?hl=fr
Create a OAuth Desktop Application credentials https://console.cloud.google.com/apis/credentials
Download the Client OAuth file and copy into your zenv
with the name oauth2-drive.keys.json
open .
npm install googleapis@105 @google-cloud/local-auth@2.1.0 --save
Run the block one time to save your authentication state (refresh_token) into token.json
//exec: node
const path = require('path');
const { google } = require('googleapis');
const {authenticate} = require('@google-cloud/local-auth');
const fs = require('fs');
const drive = google.drive('v3');
const TOKEN_PATH = path.join(__dirname, "token.json")
const CREDENTIALS_PATH = path.join(__dirname, 'oauth2-drive.keys.json') // this is your credentials file previously downloaded
const SCOPES = ['https://www.googleapis.com/auth/drive.file']
// Methods utilities to authorize and save credentials
async function loadSavedCredentialsIfExist() {
try {
const content = fs.readFileSync(TOKEN_PATH);
const credentials = JSON.parse(content);
return google.auth.fromJSON(credentials);
} catch (err) {
return null;
}
}
async function saveCredentials(auth) {
const content = fs.readFileSync(CREDENTIALS_PATH);
const keys = JSON.parse(content);
const key = keys.installed || keys.web;
const payload = JSON.stringify({
type: 'authorized_user',
client_id: key.client_id,
client_secret: key.client_secret,
refresh_token: auth.credentials.refresh_token,
});
fs.writeFileSync(TOKEN_PATH, payload);
}
async function authorize() {
let auth = await loadSavedCredentialsIfExist();
if (auth) {
return auth;
}
auth = await authenticate({
scopes: SCOPES,
keyfilePath: CREDENTIALS_PATH,
});
if (auth.credentials) {
await saveCredentials(auth);
}
return auth;
}
// load authorization
const auth = await authorize();
google.options({auth});
// Work with Drive API
const filePath = path.join(__dirname, "FILE_TO_UPLOAD.png");
console.log(filePath)
const response = await drive.files.create({
requestBody: {
name: 'FILE_TO_UPLOAD.png', //file name
mimeType: 'image/png',
},
media: {
mimeType: 'image/png',
body: fs.createReadStream(filePath),
},
});
// report the response from the request
console.log(response.data);
/*
const response = await drive.files.delete({
fileId: '1LnPv2cwtZB1JG9l0KAwtJyG7CPLZkZDg',// file id
});
console.log(response.data, response.status);
*/
https://github.com/googleapis/google-api-nodejs-client/tree/main/samples/drive