READMEの修正

This commit is contained in:
ry.yamafuji 2025-03-22 09:45:36 +09:00
parent 7febf69c0c
commit 3a1b88493f

View File

@ -9,7 +9,7 @@
- [サンプルソース](#サンプルソース)
- [Blobを使用してZIPファイルを処理する(フロント側の処理)\*\*](#blobを使用してzipファイルを処理するフロント側の処理)
- [gcloudにあるファイルをzip形式でファイルを出力するサンプルソース](#gcloudにあるファイルをzip形式でファイルを出力するサンプルソース)
- [Zipダウンロードサーバを構築する(gcloud + express)](#zipダウンロードサーバを構築するgcloud--express)
- [Zipダウンロードサーバを構築する(gcloud)](#zipダウンロードサーバを構築するgcloud)
## 圧縮処理について
@ -165,46 +165,53 @@ async function downloadAndZip() {
downloadAndZip().catch(console.error);
```
#### Zipダウンロードサーバを構築する(gcloud + express)
#### Zipダウンロードサーバを構築する(gcloud)
(サーバ)
```js
/**
* @fileoverview Google Cloud Storage (GCS) download module.
*/
const { Storage } = require('@google-cloud/storage');
const express = require('express');
const archiver = require('archiver');
const KEY_FILE_PATH = './keys/service-account.json'
const storage = new Storage({
keyFilename: KEY_FILE_PATH});
const storage = new Storage();
const bucketName = 'your-bucket-name';
// Load environment variables
require('dotenv').config();
const app = express();
const port = 3000;
// バケット名を.envから取得する
const BUCKET_NAME = process.env.BUCKET_NAME;
console.log(`BUCKET_NAME: ${BUCKET_NAME}`);
app.get('/download-zip', async (req, res) => {
const filesToDownload = ['file1.csv', 'file2.csv']; // 圧縮したいファイルリスト
/**
* GCStorageからファイルをダウンロードする
*
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
*/
const downloadFilesFromGCS = async (req, res) => {
// バケットからファイル一覧を取得する
const [files] = await storage.bucket(BUCKET_NAME).getFiles();
const filesToZip = files.map((file) => file.name);
res.setHeader('Content-Disposition', 'attachment; filename="files.zip"');
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', 'attachment; filename="compressed_files.zip"');
const archive = archiver('zip', { zlib: { level: 9 } });
archive.pipe(res); // レスポンスに直接圧縮データを送る
for (const fileName of filesToDownload) {
const file = storage.bucket(bucketName).file(fileName);
const [exists] = await file.exists();
archive.on('error', (err) => res.status(500).send({ error: err.message }));
archive.pipe(res);
if (exists) {
console.log(`Adding ${fileName} to archive...`);
archive.append(file.createReadStream(), { name: fileName });
} else {
console.warn(`File not found: ${fileName}`);
}
for (const fileName of filesToZip) {
const file = storage.bucket(BUCKET_NAME).file(fileName);
archive.append(file.createReadStream(), { name: fileName });
}
archive.finalize(); // ZIP 圧縮を完了
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
archive.finalize();
};
module.exports = downloadFilesFromGCS;
```