Usare Google Drive in Node.js

Mattepuffo's logo
Usare Google Drive in Node.js

Usare Google Drive in Node.js

Google mette a disposzione parecchie API per i suoi servizi; oggi vediamo come usare quelle per Google Drive con Javascript all'interno di una app Node.js!

Il punto di partenza, per qualsiasi API, è creare un progetto; potete iniziare con il wizard ufficiale.

Poi andate nella sezione Libreria ed attivate le API che volete, GDrive richiede delle credenziali, che potete creare nella sezione Credenziali.

Create quelle di tipo OAuth scegliendo Applicazione web.

Adesso installiamo il modulo:

# npm install googleapis@27 --save

Se avete fatto tutto, possiamo vedere il codice Javascript:

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
const TOKEN_PATH = 'credentials.json';

fs.readFile('client_secret.json', (err, content) => {
    if (err) {
        return console.log('Errore :', err);
    }
    authorize(JSON.parse(content), listFiles);
});

function authorize(credentials, callback) {
    const {client_secret, client_id, redirect_uris} = credentials.installed;
    const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
    fs.readFile(TOKEN_PATH, (err, token) => {
        if (err) {
            return getAccessToken(oAuth2Client, callback);
        }
        oAuth2Client.setCredentials(JSON.parse(token));
        callback(oAuth2Client);
    });
}

function getAccessToken(oAuth2Client, callback) {
    const authUrl = oAuth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES,
    });
    console.log('Segui il link per autorizzare la app:', authUrl);
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    rl.question('Inserisci il codice: ', (code) => {
        rl.close();
        oAuth2Client.getToken(code, (err, token) => {
            if (err) {
                return callback(err);
            }
            oAuth2Client.setCredentials(token);
            fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
                if (err) {
                    console.error(err);
                }
                console.log('Token è stato salvato in ', TOKEN_PATH);
            });
            callback(oAuth2Client);
        });
    });
}

function listFiles(auth) {
    const drive = google.drive({version: 'v3', auth});
    drive.files.list({
        pageSize: 10,
        fields: 'nextPageToken, files(id, name)',
    }, (err, {data}) => {
        if (err) {
            return console.log('ERRORE: ' + err);
        }
        const files = data.files;
        if (files.length) {
            console.log('I TUOI FILES:');
            files.map((file) => {
                console.log(`${file.name} (${file.id})`);
            });
        } else {
            console.log('No files found.');
    }
    });
}

Avviate lo script:

$ node index.js

In console apparirà una cosa del genere:

$ node index.js 
(node:3293) ExperimentalWarning: The fs.promises API is experimental
Segui il link per autorizzare la app: LINK_DA_APRIRE_NEL_BROWSER
Inserisci il codice: IL_CODICE_DA_COPIARE
Token è stato salvato in  credentials.json
I TUOI FILES:
IMG-20180425-WA0009.jpg (12xe08a1XSZJmsTzxiW5P5qRU9xHTmjsP)
IMG-20180425-WA0008.jpg (1f-bHCK1Gd50ksg4DT0mjasgtTaMGB7Jo)
IMG-20180425-WA0006.jpg (1Pc3oDCyMzel7-1rk1wQWu1A56Nz1r8I8)
IMG-20180425-WA0007.jpg (1mRrS4DD6qeZwkuAFEje2e2lC3gw7Y-GF)
IMG-20180425-WA0004.jpg (1peGbK-1Rlftn4pu3q0is-fBxlM5NQ90L)
IMG-20180425-WA0003.jpg (16i2t-kJvpH_L4Ye_JRJx1kzfPqDBvvfm)
IMG-20180425-WA0005.jpg (1nTUhaDy6rpWCF8pLookY6yZxBCfPKDD5)
IMG-20180425-WA0002.jpg (17XqSq0x1zUpigAd5aIGIE1M3GuDZvoEk)
Screenshot_20171021-010038.png (1wOl2JxSo9Ni74cDFRpJy_1HtQJgLUuZn)
Proud Story Quest Requirements (1YohOrttRtfCDlrMZ1C4eZglLGp3MzVODazTUsag9SSE)

Enjoy!


Condividi

Commentami!