NodeJS gcloud - Upload to google storage with public-read property/custom cache-expire

4.1k views Asked by At

I am trying to upload to google storage using the gcloud library (NodeJS).

I need to enable public-read property and also set the cache-expiration to 5 minutes.

I am using this (simplified) code:

storage = gcloud.storage({options}
bucker = storage.bucket('name');
fs.createReadStream(srcPath).pipe(bucket.file(targetFile).createWriteStream()).on('error', function(err) 

How do I go about setting the approprate ACL/cache expire? (I found this but not sure what to make of it: https://googlecloudplatform.github.io/gcloud-node/#/docs/v0.11.0/storage?method=acl)

Thanks for the help

3

There are 3 answers

1
Stephen On BEST ANSWER

You can set the predefined ACL following the instructions here:

yourBucket.acl.default.add({
  entity: "allUsers",
  role: gcloud.storage.acl.READER_ROLE
}, function (err) {})

Regarding cache control, I don't believe you can set this as a default, but you can set this at the time of uploading your file:

var opts = { metadata: { cacheControl: "public, max-age=300" } }
bucket.file(targetFile).createWriteStream(opts)

Reference: https://cloud.google.com/storage/docs/reference-headers#cachecontrol

0
eloone On

Api changed, use:

var gcloud = require('gcloud')({
  projectId: 'your_id',
  keyFilename: 'your_path'
});

var storage = gcloud.storage();
var bucket = storage.bucket('bucket_name');

bucket.acl.default.add({
    entity: 'allUsers',
    role: storage.acl.READER_ROLE
}, function(err) {});

To make the entire bucket public you can also use:

bucket.makePublic

Source: https://github.com/GoogleCloudPlatform/gcloud-node/blob/v0.16.0/lib/storage/bucket.js#L607

Or for just the file:

var bucketFile = bucket.file(filename);

// If you upload a new file, make sure to do this 
// in the callback of upload success otherwise it will throw a 404 error

bucketFile.makePublic(function(err) {});

Source: https://github.com/GoogleCloudPlatform/gcloud-node/blob/v0.16.0/lib/storage/file.js#L1241 (link might change, look for makePublic in the source code.)

Or:

bucketFile.acl.add({
    scope: 'allUsers',
    role: storage.acl.READER_ROLE
}, function(err, aclObject) {});

which is the verbose version.

Source: https://github.com/GoogleCloudPlatform/gcloud-node/blob/v0.16.0/lib/storage/file.js#L116

0
fsamara On

Stephen's comment is accurate, however it did not work for me as the value didnt get set. After some trial and error, turn out cacheControl (no dash) to get it to work. At the time of writing, this is not documented anywhere that it needs to be in this format. I assume other fields will have the same issue.

var opts = { metadata: { "cacheControl": "public, max-age=300" } }
bucket.file(targetFile).createWriteStream(opts)