6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Google DriveのAPIをNode.jsから触るメモ

Last updated at Posted at 2021-02-22

Google Drive API v3を触ります。
google-auth-token-generatorを使ってtoken.jsonの作成をしてみる版です。

以前書いた記事も参考に: https://qiita.com/n0bisuke/items/ff1479cd14e7a0c0be0c

環境

  • Node.js v15.9.0

credentials.jsonを取得

チュートリアルを参考にAPIを有効にし、credentials.jsonを手元に保存しましょう。

https://developers.google.com/drive/api/v3/quickstart/nodejs

google-auth-token-generatorでtoken.jsonを作成

google-auth-token-generatorを使うとパーミッションをつけたtoken.jsonを作成しやすいです。

利用イメージ

credentials.jsonのあるディレクトリで、以下を実行します。

$ npx google-auth-token-generator

GoogleDriveを選択し、パーミッションを選択して進めましょう。

ファイルの一覧取得のパーミッションはdrive.metadata.readonlyになります。

https://www.googleapis.com/auth/drive.metadata.readonly

token.jsonが保存されます。

app.jsを作成

credentials.jsontoken.jsonと同じディレクトリにapp.jsを作成する想定です。

app.js
'use strict';

const fs = require('fs');
const {google} = require('googleapis');

const googleAuth = () => {
  const CREDENTIALS_PATH = 'credentials.json';
  const TOKEN_PATH = 'token.json';  
  const credentials = JSON.parse(fs.readFileSync(CREDENTIALS_PATH, 'utf8'));
  const token = JSON.parse(fs.readFileSync(TOKEN_PATH, 'utf8'));

  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
  oAuth2Client.setCredentials(token);
  
  return oAuth2Client;
};

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

  try {
    const res = await drive.files.list({
      pageSize: 10,
      fields: 'nextPageToken, files(id, name)',
    });
  
    const files = res.data.files;
    if (files.length) {
      console.log('Files:');
      files.map((file) => console.log(`${file.name} (${file.id})`));
    } else {
      console.log('No files found.');
    }
  } catch (error) {
    console.log('The API returned an error: ' + error);
  }

})();
$ node app.js

参考記事

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?