const authCloudImplicit = async () => { // [START auth_cloud_implicit] // Imports the Google Cloud client library. const {Storage} = require('@google-cloud/storage'); // Instantiates a client. If you don't specify credentials when constructing // the client, the client library will look for credentials in the // environment. const storage = new Storage(); try { // Makes an authenticated API request. const results = await storage.getBuckets(); const [buckets] = results; console.log('Buckets:'); buckets.forEach(bucket => { console.log(bucket.name); }); } catch (err) { console.error('ERROR:', err); } // [END auth_cloud_implicit] }
// Process the file upload and upload to Google Cloud Storage. app.post('/upload', multer.single('file'), (req, res, next) => { if (!req.file) { res.status(400).send('No file uploaded.'); return; } // Create a new blob in the bucket and upload the file data. const blob = bucket.file(req.file.originalname); const blobStream = blob.createWriteStream({ resumable: false, }); blobStream.on('error', err => { next(err); }); blobStream.on('finish', () => { // The public URL can be used to directly access the file via HTTP. const publicUrl = format( `https://storage.googleapis.com/${bucket.name}/${blob.name}` ); res.status(200).send(publicUrl); }); blobStream.end(req.file.buffer); });
const authCloudExplicit = async ({projectId, keyFilename}) => { // [START auth_cloud_explicit] // Imports the Google Cloud client library. const {Storage} = require('@google-cloud/storage'); // Instantiates a client. Explicitly use service account credentials by // specifying the private key file. All clients in google-cloud-node have this // helper, see https://github.com/GoogleCloudPlaatform/google-cloud-node/blob/master/docs/authentication.md // const projectId = 'project-id' // const keyFilename = '/path/to/keyfile.json' const storage = new Storage({projectId, keyFilename}); // Makes an authenticated API request. try { const [buckets] = await storage.getBuckets(); console.log('Buckets:'); buckets.forEach(bucket => { console.log(bucket.name); }); } catch (err) { console.error('ERROR:', err); } // [END auth_cloud_explicit] }