Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8691

Node.jsでGoogle Drive上にフォルダ作成と存在確認 (Google Drive API v3)

$
0
0

Google Drive上でフォルダを作成します。

メソッドはFiles: createになります。

ライブラリの書き方だとdrive.files.create()です。

スコープ指定

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

Google Drive上で新規フォルダ作成

チュートリアルfunction listFilesの箇所を書き換えて利用してみます。

機能的にはfunction createFolderとかにリネームした方が良いでしょうが一旦動かす体なのでスルー

createFolder.js
//省略asyncfunctionlistFiles(auth){constdrive=google.drive({version:'v3',auth});constfileMetadata={'name':'n0bisuke',//作成したいフォルダの名前'mimeType':'application/vnd.google-apps.folder'};constparams={resource:fileMetadata,fields:'id'}try{constres=awaitdrive.files.create(params);console.log(res.data);}catch(error){console.log(error);}};

マイドライブのルートにn0bisukeというフォルダが作成されます。

フォルダを指定してフォルダ内にフォルダを新規作成

requestBodyにparents,name,mimeTypeを指定して実行します。

//省略asyncfunctionlistFiles(auth){constdrive=google.drive({version:'v3',auth});constparams={fields:'id',requestBody:{name:'n0bisuke',//新規作成するフォルダの名前mimeType:'application/vnd.google-apps.folder'parents:[`xxxxxxxxxxxxxxxxxxxxxxx`],//新規作成したフォルダを置くフォルダのID}}try{constres=awaitdrive.files.create(params);console.log(res.data);}catch(error){console.log(error);}};

応用: 同名のフォルダが存在しなければフォルダを新規作成する

フォルダを自動的に作ったりするときに使いそうなのでメモしておきます。

  1. フォルダの確認
  2. 作成

という2ステップが考えられます。

1. 既に同じ名前のフォルダがあるかどうかの確認

Google Driveだと同じ名前のフォルダを同じ階層に作成することができてしまうので、防ぎたい場合は存在チェックを先にした方が良いと思います。(メソッドがなさそうな気がしたので手動)

FOLDER_IDで指定したフォルダの中を.list()で確認し、n0bisukeという名前のフォルダがあるか無いかをチェックします。

//省略asyncfunctionlistFiles(auth){constnewFolderName=`n0bisuke`;//調べたいフォルダ名constdrive=google.drive({version:'v3',auth});constFOLDER_ID=`xxxxxxxxxxxxxxxx`;//ここにフォルダIDを指定constparams={q:`'${FOLDER_ID}' in parents and trashed = false`,}constres=awaitdrive.files.list(params);constexists=res.data.files.find(file=>file.name===newFolderName);if(exists){console.log(`${newFolderName}は存在します。`);}else{console.log(`${newFolderName}は存在しません。`);}};

2. フォルダの作成まで

まとめて書くとこんな感じです。

//省略asyncfunctionlistFiles(auth){constnewFolderName=`n0bisuke`;//調べたいフォルダ名constFOLDER_ID=`xxxxxxxxxxxxxxxxxxxxxx`;//ここにフォルダIDを指定constdrive=google.drive({version:'v3',auth});constparams={q:`'${FOLDER_ID}' in parents and trashed = false`,}constres=awaitdrive.files.list(params);constexists=res.data.files.find(file=>file.name===newFolderName);if(exists){console.log(`${newFolderName}は存在します。`);}else{console.log(`${newFolderName}は存在しません。`);console.log(`フォルダを新規作成します。`)constparams={fields:'id',requestBody:{parents:[FOLDER_ID],name:newFolderName,mimeType:'application/vnd.google-apps.folder'}}constres=awaitdrive.files.create(params);console.log(res.data);}};

これで特定のフォルダ内にn0bisukeフォルダがあれば何もせず、n0bisukeフォルダが存在しなければ新規作成してくれます。

よもやま

.create()の時に重複を許可しない指定っぽいのができればこんなの周りくどいことしなくてよいのでもしそんな指定の仕方知ってる人いたら教えてください。


Viewing all articles
Browse latest Browse all 8691

Trending Articles