📁

GoogleDriveAPIでファイル総数を数えてみる

に公開

🧭 概要

Google Drive APIを使って特定のメールアドレスに共有されているファイルの総数を検索する処理を書く機会があったので覚書

🪗 準備1

Google Drive APIを動かすにはGoogleアカウントを用いて準備が必要なのでまずはここから

1. Googleアカウントを作成

すでに持っている場合はそれを使ってもOK

2. Google Cloudを有効にする

該当のGoogleアカウントにアクセスし、右上付近の「コンソール」を押下

押すとこんな感じ

3. プロジェクトの作成

My First Projectを押して

新しいプロジェクトを押下

分かりやすい名前を入れて「作成」を押下

すると先ほどのMy First Projectをもう一度押すと作成したプロジェクトが表示されている

4. Google Drive APIの有効化

プロジェクトを選択したあと、左上のハンバーガーメニューを押下しAPIとサービス > 有効なAPIサービスを押下

検索画面で「Google Drive API」と入力し、検索結果の「有効にする」を押下

5. 認証情報の作成

サイドバーの「認証情報」を押下し、上部の認証情報を作成 > サービスアカウントを押下

サービスアカウント名、サービスアカウントIDを入力し「完了」を押下

更新するとサービスアカウントに作成したものが表示されるので押下

メニューの「鍵」を押下しキーを追加 > 新しい鍵を作成を押下

JSONを選択し作成すると認証情報がダウンロードされる
今後使用するので分かりやすい場所に分かりやすい名前で保存しておく

こんな感じのものがダウンロードされていればOK
※ 本当は全項目記載があるけどセキュリティ面で削除

{
  "type": "",
  "project_id": "",
  "private_key_id": "",
  "private_key": "",
  "client_email": "",
  "client_id": "",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "",
  "universe_domain": "googleapis.com"
}

🦋 準備2

手元で動かすにはサーバーが必要らしいとのことでここら辺のinit & installをしてあげる

 npm init -y
 npm install express googleapis cors

🖊️ 書き方

サーバ側の処理 server.js に以下を記載

const express = require('express');
const { google } = require('googleapis');
const cors = require('cors');

const app = express();
app.use(cors());

// サービスアカウントの認証情報
const credentials = require('[準備1でダウンロードした認証情報のJSON]');

// Google Drive APIクライアントの初期化
const auth = new google.auth.GoogleAuth({
  credentials,
  scopes: ['https://www.googleapis.com/auth/drive.readonly']
});

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

app.get('/count-files', async (req, res) => {
  try {
    console.log('🌟 API呼び出し開始');
    let totalFiles = 0;
    let pageToken = null;

    do {
      const response = await drive.files.list({
        pageSize: 1000,
        fields: 'nextPageToken, files(id)',
        pageToken: pageToken
      });

      console.log('Accessible folders:', response.data.files);

      totalFiles += response.data.files.length;
      pageToken = response.data.nextPageToken;
    } while (pageToken);

    res.json({ count: totalFiles });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: error.message });
  }
});

app.listen(3000, () => {
  console.log('🚀 サーバーが起動しました - ポート3000');
  console.log('📧 使用中のサービスアカウント:', credentials.client_email);
});

✅ 確認方法

ボタンを押したら走るindex.htmlとindex.jsを書く

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Google Driveファイルカウンター</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
        }
        button {
            padding: 15px 30px;
            font-size: 16px;
            cursor: pointer;
            background-color: #4285f4;
            color: white;
            border: none;
            border-radius: 4px;
        }
        button:hover {
            background-color: #357abd;
        }
        #result {
            margin-top: 20px;
            font-size: 16px;
        }
    </style>
    <script src="https://apis.google.com/js/api.js"></script>
</head>
<body>
    <button onclick="countFiles()">ファイル数を取得</button>
    <div id="result"></div>
    <script src="new.js"></script>
</body>
</html>
index.js
function countFiles() {
  console.log('countFiles');

  fetch('http://localhost:3000/count-files')
    .then(response => response.json())
    .then(data => {
      document.getElementById('result').textContent =
        `Google Driveのファイル数: ${data.count}`;
    })
    .catch(error => {
      console.error('エラーが発生しました:', error);
      document.getElementById('result').textContent =
        'エラーが発生しました。コンソールを確認してください。';
    });
}

VSCodeのLive Serverを立ち上げて

node server.js

をしてボタン押したら動く

Discussion