Created
September 5, 2017 08:04
-
-
Save joduplessis/0fa6b81ed9cfc7ca6cd665eb9312922a to your computer and use it in GitHub Desktop.
Add images to Google Cloud Storage (inc. Firebase) using NodeJS.
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
/* | |
* 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