LoginSignup
4
4

More than 5 years have passed since last update.

単にJSONをGoogle Cloud Storageに保存したいだけ

Posted at

なのに、意外と困ってしまい、備忘録。

これでいいっぽい

const { Storage } = require('@google-cloud/storage');
const { Readable } = require('stream');
const gcs = new Storage({
    projectId: '<YOUR_PROJECT_NAME>'
});

const data = [
    { key: 'value' },
    { key: 'value' }
    // ...
];

// Writing GCS
const file = gcs.bucket('<YOUR_BUCKET>').file(`<YOUR_FILE_PATH>.json`);
const gcsStream = file.createWriteStream({
    metadata: {
        cacheControl: 'no-cache',
        contentType: 'application/json'
    }
});
const readStream = new Readable();
readStream.push(data.map(d => JSON.stringify(d)).join('\n'));
readStream.push(null);

readStream
    .on('error', error => {
        console.error('Stream error');
        res.status(500).send(JSON.stringify(error));
    })
    .pipe(gcsStream)
    .on('error', error => {
        console.error('Stream error');
        res.status(500).send(JSON.stringify(error));
    })
    .on('finish', () => {
        console.log('Stream writig to GCS is completed');
        res.send({ status: 'success' });
    });

定期バッチなんかをFunctionsに書いておいて、Cloud Scheduler(betaだけど) -> Functions -> GCS -> BigQuery でググれる(広義)ようにしておけば、ちょっとしたログ基盤すぐに作れて便利。

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