LoginSignup
7
3

More than 5 years have passed since last update.

node.jsでGoogleCloudStorageに文字列データをファイルとしてアップロードする

Last updated at Posted at 2018-08-26

もうそのまんまです。難しそうなことは一切なさそうです。
JSONフォーマットのString型のデータが存在するので、@google-cloud/storageを使用して、アップロードしてみます。

手っ取り早くソースを見たい方向け:relaxed:

実際に動かしてみた結果:yum:

Bucket.prototype.uploadでは対応できない:sob:

bucket.upload('/local/path/image.png', function(err, file, apiResponse) {
  // Your bucket now contains:
  // - "image.png" (with the contents of `/local/path/image.png')

  // `file` is an instance of a File object that refers to your new file.
});

bucket.upload('https://example.com/images/image.png', function(err, file, apiResponse) {
  // Your bucket now contains:
  // - "image.png"

  // `file` is an instance of a File object that refers to your new file.
});

Bucketクラスのupload functionのサンプルです。
この関数を使用すると簡単にアップロードできるんですが、ファイルのパスを指定してアップロードする必要が出てきてしまいます。
さすがに文字列データを一回ファイルに落として、それからアップロードするというのも非常にめんどくさいので、FileクラスのcreateWriteStreamを使用してアップロードしてあげる必要がありそうです。

createWriteStreamの呼び出し方

fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
  .pipe(file.createWriteStream())
  .on('error', function(err) {})
  .on('finish', function() {
    // The file upload is complete.
  });

createWriteStreamのサンプルです。
これもサンプルではファイルが対象なんですが、readStreamに対象の文字列を投入してあげれば行けそうです。

実装例:nerd:

const storageClient = Storage();
const bucket = storageClient.bucket(process.env.UPLOAD_BUCKET);

const uploadFile = bucket.file(uploadPath);
const uploadStream = uploadFile.createWriteStream({
  predefinedAcl: 'publicRead',
  metadata: {
    cacheControl: 'no-cache',
    contentType: 'text/plain',
  },
});

const readStream = new Readable();
readStream.push(text);
readStream.push(null);

readStream
  .on('error', reject)
  .pipe(uploadStream)
  .on('error', reject)
  .on('finish', resolve);

こんな感じになっています。
読み込み用のStreamを作成し、そこにtextを設定。
そのまま、upload用のstreamに流れるようにしています。
これでアップロードできるようになりました:v:

最後に

株式会社ネコカリでは猫の手も借りたい🔥炎上中🔥なお仕事を募集しています!
一緒に働くメンバーも募集していますので、よかったら是非!

7
3
11

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
7
3