Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Created September 5, 2017 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joduplessis/0fa6b81ed9cfc7ca6cd665eb9312922a to your computer and use it in GitHub Desktop.
Save joduplessis/0fa6b81ed9cfc7ca6cd665eb9312922a to your computer and use it in GitHub Desktop.
Add images to Google Cloud Storage (inc. Firebase) using NodeJS.
/*
* Example for adding images to Google Cloud Storage using NodeJS.
* This integrates with Firebase, you just need to download the keyfile.
* Firebase project > Settings > Firebase Admin SDK > Generate new private key.
* Don't forget to install dependancies: "yarn add bluebird @google-cloud/storage"
*/
const projectId = 'xxx'
const bucketName = projectId+'.appspot.com'
const Promise = require('bluebird');
const GoogleCloudStorage = Promise.promisifyAll(require('@google-cloud/storage'));
const storage = GoogleCloudStorage({
projectId: projectId,
keyFilename: 'xxx.json'
})
const myBucket = storage.bucket(bucketName)
const file = myBucket.file('xxx.jpg');
const localFileLocation = './xx.jpg'
file.existsAsync()
.then(exists => {
if (exists) {
console.log('File already exists.')
}
})
.catch(err => {
return err
})
myBucket.uploadAsync(localFileLocation, { public: true })
.then(file => {
console.log('Uploaded.')
})
const getPublicThumbnailUrlForItem = file_name => {
return `https://storage.googleapis.com/${bucketName}/${file_name}`
}
getPublicThumbnailUrlForItem(localFileLocation);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment