@google-cloud/storage
是 Google Cloud Storage 的 Node.js 客戶端程式庫,允許開發者輕鬆地與 Google Cloud Storage 服務進行交互。本文將深入探討如何在 Node.js 應用程式中使用此程式庫,並提供一些常見用例的範例。
1. 安裝
首先,使用 npm 或 yarn 安裝 @google-cloud/storage
套件:
npm install @google-cloud/storage
2. 初始化
在你的 Node.js 程式碼中,你需要使用你的 Google Cloud 專案憑證初始化 Storage 客戶端。有以下兩種方式:
- 使用服務帳戶憑證:
const { Storage } = require('@google-cloud/storage');
const storage = new Storage({
keyFilename: 'path/to/your/service-account-key.json',
});
- 使用預設應用程式憑證:
如果你使用的是 Google Cloud Platform 的預設應用程式憑證,你不需要明確提供憑證檔路徑,程式庫將自動使用預設憑證:
const { Storage } = require('@google-cloud/storage');
const storage = new Storage();
3. 常見操作
以下是使用 @google-cloud/storage
程式庫的一些常見操作:
- 上傳檔案:
const bucketName = 'your-bucket-name';
const fileName = 'your-file-name.txt';
const filePath = 'path/to/your/file.txt';
const [file] = await storage
.bucket(bucketName)
.upload(filePath, {
destination: fileName,
});
console.log(`File ${fileName} uploaded to ${file.name}`);
- 下載檔案:
const bucketName = 'your-bucket-name';
const fileName = 'your-file-name.txt';
const destination = 'path/to/your/download/location.txt';
const [file] = await storage
.bucket(bucketName)
.file(fileName)
.download({
destination,
});
console.log(`File ${fileName} downloaded to ${destination}`);
- 刪除檔案:
const bucketName = 'your-bucket-name';
const fileName = 'your-file-name.txt';
await storage
.bucket(bucketName)
.file(fileName)
.delete();
console.log(`File ${fileName} deleted`);
- 列出檔案:
const bucketName = 'your-bucket-name';
const [files] = await storage
.bucket(bucketName)
.getFiles();
console.log('Files:');
files.forEach((file) => {
console.log(file.name);
});
4. 進階操作
除了以上基本操作,@google-cloud/storage
程式庫還提供許多進階功能,例如:
- 檔案元數據管理: 可以設定和存取檔案的元數據,例如內容類型、標籤等。
- 檔案存取控制: 可以設定檔案的存取控制列表 (ACL),控制不同使用者或群組對檔案的訪問權限。
- 檔案事件監控: 可以使用事件通知功能,監控檔案的各種事件,例如新增、修改、刪除等。
- 檔案流式傳輸: 可以使用流式傳輸 API,在不將整個檔案載入記憶體的情況下上傳和下載檔案。
5. 總結
@google-cloud/storage
程式庫為 Node.js 開發者提供了一個強大的工具,使他們能夠輕鬆地與 Google Cloud Storage 進行交互。通過使用此程式庫,開發者可以輕鬆地存取、管理和操作儲存在 Google Cloud Storage 中的檔案,並使用其豐富的功能來滿足各種需求。
以上內容由gemini產生。