LoginSignup
2
1

More than 3 years have passed since last update.

Node.jsでGoogle Drive上のファイルを複製(copy)する (Google Drive API v3)

Last updated at Posted at 2019-07-14

前に書いたNode.jsでGoogle Driveの指定フォルダからファイル一覧を取得メモの続きです。

メソッドはこちらのcopyを使います。

スコープ

https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/drive.appdata
https://www.googleapis.com/auth/drive.photos.readonly

の四つを許可する必要があるみたいです。

公式チュートリアルのコードを元に編集します。

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

copy.js
省略

const SCOPES = [
    `https://www.googleapis.com/auth/drive`,
    `https://www.googleapis.com/auth/drive.file`,
    `https://www.googleapis.com/auth/drive.appdata`,
    `https://www.googleapis.com/auth/drive.photos.readonly`,
];


省略

みたいに記述しましょう。

drive.files.copy()

チュートリアルコードのlistFiles関数をmain関数として定義しなおして以下のように呼び出します。

copy.js
//省略

function main(auth) {
    const targetFileId = `xxxxxxxxxxxxxxxxxxxxxxx`; //コピーしたいファイルID
    const drive = google.drive({version: 'v3', auth});
    const params = {
        fileId: targetFileId
    };

    drive.files.copy(params)
    .then(res => console.log(res))
    .catch(err => console.log(err));
}

試してみる

実行すると

こんな感じで同じフォルダーにコピーされます。

GaxiosError: Insufficient Permission: Request had insufficient authentication scopes.
    at Gaxios.request (/Users/n0bisuke/dotstudio/playground/gdrive/node_modules/gaxios/build/src/gaxios.js:70:23)

的なエラーがでる場合がありますが、token.jsonがすでに別のスコープで作成されてるときは公式チュートリアルのコードだと再認証されないので、token.jsonを一回削除してから試してみましょう。

別フォルダにコピーするのは別のメソッドが必要な模様なので調べて別記事にしてみます。

2
1
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
2
1