Install Required Libraries
- Ensure you have Node.js and npm installed on your machine.
- Install the Google Cloud client library for Node.js to interact with Google Cloud Storage. Execute the following command in your terminal:
npm install @google-cloud/storage
Set Up Authentication
- Download your Google Cloud Platform service account key.json file after creating a service account with necessary permissions (e.g., Storage Admin).
- Set the environment variable to authenticate your requests. You can do it by running:
export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/key.json"
Initialize the Google Cloud Storage Client
- Initialize the Google Cloud Storage client in your Node.js application with the following code:
const {Storage} = require('@google-cloud/storage');
// Initialize the client with your project ID and credentials
const storage = new Storage();
Accessing Buckets
- To list all buckets in your project, you can use:
async function listBuckets() {
try {
const [buckets] = await storage.getBuckets();
console.log('Buckets:');
buckets.forEach(bucket => console.log(bucket.name));
} catch (err) {
console.error('ERROR:', err);
}
}
listBuckets();
Interacting with Objects
- To upload an object, use the following code snippet:
async function uploadFile(bucketName, filename) {
try {
await storage.bucket(bucketName).upload(filename, {
gzip: true,
});
console.log(`${filename} uploaded to ${bucketName}.`);
} catch (err) {
console.error('ERROR:', err);
}
}
- To download an object, try this code:
async function downloadFile(bucketName, srcFilename, destFilename) {
try {
const options = {
destination: destFilename,
};
await storage.bucket(bucketName).file(srcFilename).download(options);
console.log(`Downloaded ${srcFilename} to ${destFilename}.`);
} catch (err) {
console.error('ERROR:', err);
}
}
Setting Object Metadata
- You can set metadata for objects using:
async function setMetadata(bucketName, filename, metadata) {
try {
await storage.bucket(bucketName).file(filename).setMetadata(metadata);
console.log(`Metadata set for file ${filename}:`, metadata);
} catch (err) {
console.error('ERROR:', err);
}
}
Handle Errors Gracefully
- Always encapsulate API calls in try-catch blocks to manage exceptions and log errors properly, ensuring reliability and debugging ease.
Best Practices
- Use the latest version of the Google Cloud client library to ensure support and security.
- Securely manage service account keys; restrict access and rotate periodically to mitigate security risks.
- Consider using Google Cloud's IAM roles and permissions to finely grain access controls.