Last active
June 26, 2023 17:24
-
-
Save antarikshc/ec6d6c59e50e955895bc4b21cf7b4a59 to your computer and use it in GitHub Desktop.
Code sample to upload files in Google Cloud Storage bucket for Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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