iMind Developers Blog

iMind開発者ブログ

nodeでGCPのCloud Storageの操作

概要

公式のドキュメントが今ひとつわかりづらかったので個人的によく使う下記の処理の使い方をメモしておく。

  • バケットの生成
  • アップロード
  • ls
  • ダウンロード
  • ファイルの削除

バージョン情報

  • "@google-cloud/storage": "^4.1.1"
  • "fast-crc32c": "^2.0.0"

導入

$ npm install --save @google-cloud/storage
$ npm install --save fast-crc32c

バケットの生成

const {Storage} = require('@google-cloud/storage');

const keyFilename = 'サービスアカウントのキーファイル';
const bucketName = 'my-example-bucket';

// バケットの取得
const storage = new Storage({keyFilename: keyFilename});
const bucket = storage.bucket(bucketName);

// バケットの生成
bucket.create(function(err, bucket, apiResponse) {
    if (!err) {
        console.log(bucket);
    } else {
        console.log(err);
    }
});

ファイルのアップロード

bucket.upload('example.txt',
    {'destination': 'dest/example.txt'});

ls

cliで書くと下記のような処理。

$ gsutil ls gs://bucket_name/

nodeの場合。

bucket.getFiles()
    .then(data => {
        let files = data[0];
        files.forEach(file => {
            console.log(file.name);
        });
    })
    .catch( ex => console.log(ex) );

prefixを指定すると指定パスで始まるファイルのみ取れる。

bucket.getFiles({'prefix': 'dest/'})

ファイルのダウンロード

bucket.file('dest/example.txt')
  .download({'destination': 'example_dl.txt'})
  .then(() => {})

ファイルの削除

bucket.file('dest/example.txt')
  .delete()
  .then(data => {})

改定履歴

Author: Masato Watanabe, Date: 2019-11-16, 記事投稿