google drive | | test list google drive | Search

The code requires various modules and defines several variables for interacting with the Google API, specifically the Google Drive API. It includes a function called authorizeDrive that authenticates with the Google API using a credentials file and returns a client instance for the Google Drive API.

Run example

npm run import -- "authorize google drive"

authorize google drive

var fs = require('fs');
var path = require('path');
var {google} = require('googleapis');
var {GoogleAuth} = require('google-auth-library');

var PROFILE_PATH = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
var credentials;
if(fs.existsSync('./sheet to web-8ca5784e0b05.json')) {
    credentials = path.resolve('./sheet to web-8ca5784e0b05.json');
} else {
    credentials = path.join(PROFILE_PATH, '.credentials/sheet to web-8ca5784e0b05.json');
}

var GOOGLE_AUTH_SCOPE = [
    'https://www.googleapis.com/auth/drive'
];

function authorizeDrive() {
    return new GoogleAuth({
        keyFile: credentials,
        scopes: GOOGLE_AUTH_SCOPE
    }).getClient()
        .then(client => google.drive({version: 'v3', auth: client}))
}

module.exports = authorizeDrive;

What the code could have been:

const fs = require('fs');
const path = require('path');
const { google } = require('googleapis');
const { GoogleAuth } = require('google-auth-library');

// Define constants for profile path and credentials file
const PROFILE_PATH = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
const CREDENTIALS_FILE = './sheet to web-8ca5784e0b05.json';
const GOOGLE_AUTH_SCOPE = [
  'https://www.googleapis.com/auth/drive'
];

// Load credentials file from path
function loadCredentials() {
  const credentialsPath = fs.existsSync(CREDENTIALS_FILE)
   ? path.resolve(CREDENTIALS_FILE)
    : path.join(PROFILE_PATH, '.credentials/', CREDENTIALS_FILE);
  return fs.readFileSync(credentialsPath, 'utf8');
}

// Load credentials from JSON string
function parseCredentials(credentials) {
  return JSON.parse(credentials);
}

// Authorize Google Drive
async function authorizeDrive() {
  // Load credentials
  const credentialsStr = loadCredentials();
  const credentials = parseCredentials(credentialsStr);

  // Create GoogleAuth instance
  const googleAuth = new GoogleAuth({
    keyFile: credentials,
    scopes: GOOGLE_AUTH_SCOPE
  });

  try {
    // Get client instance
    const client = await googleAuth.getClient();
    // Get Google Drive API client
    const drive = google.drive({ version: 'v3', auth: client });
    return drive;
  } catch (error) {
    // Handle auth error
    console.error('Auth error:', error);
    throw error;
  }
}

module.exports = authorizeDrive;

Code Breakdown

Requirements and Variables

Credentials File

Authorization Function

Note