Skip to content

Instantly share code, notes, and snippets.

@The-Anton
Forked from antarikshc/gcp-storage.js
Created August 25, 2022 23:20
Show Gist options
  • Save The-Anton/43f7c8f140081e7ea5a2e006e6f221a1 to your computer and use it in GitHub Desktop.
Save The-Anton/43f7c8f140081e7ea5a2e006e6f221a1 to your computer and use it in GitHub Desktop.
Code sample to upload files in Google Cloud Storage bucket for Node.js
// Install GCP Client library
// npm install --save @google-cloud/storage
// To run the client library, you must first set up authentication by creating a service account
// and setting an environment variable. Ask your DevOps person to provide you with service account key
// For example:
// export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"
// Imports the Google Cloud client library
const { Storage } = require('@google-cloud/storage');
// Creates a GCP Storage client
const storage = new Storage({
projectId: "some-random-id-1337",
});
// Declare the bucket you wanna upload the files
const bucketName = "exact-bucket-name";
//
// Downloading non-public file
//
const srcFilename = "download.zip";
const destFilename = "./download.zip";
// Downloads the file from bucket
await storage
.bucket(bucketName)
.file(srcFilename)
.download({
destination: destFilename
});
console.log(`GS://${bucketName}/${srcFilename} downloaded to ${destFilename}.`);
//
// Uploading a local file to the bucket
//
await storage.bucket(bucketName).upload("./filename.jpg", {
destination: "/destination/at/bucket",
// Support for HTTP requests made with `Accept-Encoding: gzip`
gzip: true,
metadata: {
// Enable long-lived HTTP caching headers
// Use only if the contents of the file will never change
// (If the contents will change, use cacheControl: 'no-cache')
cacheControl: 'public, max-age=31536000',
},
});
// Upload FileStream
const file = bucket.file(gcsname);
const stream = file.createWriteStream({
metadata: {
contentType: req.file.mimetype
},
resumable: false
});
stream.on('error', (err) => {
req.file.cloudStorageError = err;
next(err);
});
stream.on('finish', () => {
req.file.cloudStorageObject = gcsname;
file.makePublic().then(() => {
req.file.cloudStoragePublicUrl = getPublicUrl(gcsname);
next();
});
});
stream.end(req.file.buffer);
console.log(`GS://${fileName} uploaded to ${bucketName}.`);
// This will upload the file but it won't be publicly available
// To make a file public
await storage
.bucket(bucketName)
.file(filename)
.makePublic();
console.log(`gs://${bucketName}/${filename} is now public.`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment