Methods

addLifecycleRule(rule[, options][, callback]) → Promise containing SetBucketMetadataResponse

Add an object lifecycle management rule to the bucket.

By default, an Object Lifecycle Management rule provided to this method will be included to the existing policy. To replace all existing rules, supply the options argument, setting append to false.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

//-
// Automatically have an object deleted from this bucket once it is 3 years
// of age.
//-
bucket.addLifecycleRule({
  action: 'delete',
  condition: {
    age: 365 * 3 // Specified in days.
  }
}, function(err, apiResponse) {
  if (err) {
    // Error handling omitted.
  }

  const lifecycleRules = bucket.metadata.lifecycle.rule;

  // Iterate over the Object Lifecycle Management rules on this bucket.
  lifecycleRules.forEach(lifecycleRule => {});
});

//-
// By default, the rule you provide will be added to the existing policy.
// Optionally, you can disable this behavior to replace all of the
// pre-existing rules.
//-
const options = {
  append: false
};

bucket.addLifecycleRule({
  action: 'delete',
  condition: {
    age: 365 * 3 // Specified in days.
  }
}, options, function(err, apiResponse) {
  if (err) {
    // Error handling omitted.
  }

  // All rules have been replaced with the new "delete" rule.

  // Iterate over the Object Lifecycle Management rules on this bucket.
  lifecycleRules.forEach(lifecycleRule => {});
});

//-
// For objects created before 2018, "downgrade" the storage class.
//-
bucket.addLifecycleRule({
  action: 'setStorageClass',
  storageClass: 'COLDLINE',
  condition: {
    createdBefore: new Date('2018')
  }
}, function(err, apiResponse) {});

//-
// Delete objects created before 2016 which have the Coldline storage
// class.
//-
bucket.addLifecycleRule({
  action: 'delete',
  condition: {
    matchesStorageClass: [
      'COLDLINE'
    ],
    createdBefore: new Date('2016')
  }
}, function(err, apiResponse) {});

Parameters

Name Type Optional Description

rule

LifecycleRule

 

The new lifecycle rule to be added to objects in this bucket.

Values in rule have the following properties:

Name Type Optional Description

storageClass

string

Yes

When using the setStorageClass action, provide this option to dictate which storage class the object should update to.

options

AddLifecycleRuleOptions

Yes

Configuration object.

Values in options have the following properties:

Name Type Optional Description

append

boolean

Yes

Append the new rule to the existing policy.

Defaults to true.

callback

SetBucketMetadataCallback

Yes

Callback function.

See also

Object Lifecycle Management

Buckets: patch API Documentation

Returns

Promise containing SetBucketMetadataResponse 

combine(sources, destination[, options][, callback]) → Promise containing CombineResponse

Combine multiple files into one new file.

Example

const logBucket = storage.bucket('log-bucket');

const sources = [
  logBucket.file('2013-logs.txt'),
  logBucket.file('2014-logs.txt')
];

const allLogs = logBucket.file('all-logs.txt');

logBucket.combine(sources, allLogs, function(err, newFile, apiResponse) {
  // newFile === allLogs
});

//-
// If the callback is omitted, we'll return a Promise.
//-
logBucket.combine(sources, allLogs).then(function(data) {
  const newFile = data[0];
  const apiResponse = data[1];
});

Parameters

Name Type Optional Description

sources

(Array of string or Array of File)

 

The source files that will be combined.

destination

(string or File)

 

The file you would like the source files combined into.

options

CombineOptions

Yes

Configuration options.

callback

CombineCallback

Yes

Callback function.

See also

Objects: compose API Documentation

Throws

Error 

if a non-array is provided as sources argument.

Error 

if less than two sources are provided.

Error 

if no destination is provided.

Returns

Promise containing CombineResponse 

create([metadata][, callback]) → Promise containing CreateBucketResponse

Create a bucket.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');
bucket.create(function(err, bucket, apiResponse) {
  if (!err) {
    // The bucket was created successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.create().then(function(data) {
  const bucket = data[0];
  const apiResponse = data[1];
});

Parameters

Name Type Optional Description

metadata

CreateBucketRequest

Yes

Metadata to set for the bucket.

callback

CreateBucketCallback

Yes

Callback function.

Returns

Promise containing CreateBucketResponse 

createChannel(id, config[, options][, callback]) → Promise containing CreateChannelResponse

Create a channel that will be notified when objects in this bucket changes.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');
const id = 'new-channel-id';

const config = {
  address: 'https://...'
};

bucket.createChannel(id, config, function(err, channel, apiResponse) {
  if (!err) {
    // Channel created successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.createChannel(id, config).then(function(data) {
  const channel = data[0];
  const apiResponse = data[1];
});

Parameters

Name Type Optional Description

id

string

 

The ID of the channel to create.

config

CreateChannelConfig

 

Configuration for creating channel.

options

CreateChannelOptions

Yes

Configuration options.

callback

CreateChannelCallback

Yes

Callback function.

See also

Objects: watchAll API Documentation

Throws

Error 

If an ID is not provided.

Error 

If an address is not provided.

Returns

Promise containing CreateChannelResponse 

createNotification(topic[, options][, callback]) → Promise containing CreateNotificationResponse

Creates a notification subscription for the bucket.

Examples

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const callback = function(err, notification, apiResponse) {
  if (!err) {
    // The notification was created successfully.
  }
};

myBucket.createNotification('my-topic', callback);

//-
// Configure the nofiication by providing Notification metadata.
//-
const metadata = {
  objectNamePrefix: 'prefix-'
};

myBucket.createNotification('my-topic', metadata, callback);

//-
// If the callback is omitted, we'll return a Promise.
//-
myBucket.createNotification('my-topic').then(function(data) {
  const notification = data[0];
  const apiResponse = data[1];
});

include:samples/notifications.js

region_tag:storage_create_notification
Another example:

Parameters

Name Type Optional Description

topic

(Topic or string)

 

The Cloud PubSub topic to which this subscription publishes. If the project ID is omitted, the current project ID will be used.

Acceptable formats are:
- `projects/grape-spaceship-123/topics/my-topic`
  • my-topic

options

CreateNotificationOptions

Yes

Metadata to set for the notification.

callback

CreateNotificationCallback

Yes

Callback function.

See also

Notifications: insert

Notification#create
Throws

Error 

If a valid topic is not provided.

Returns

Promise containing CreateNotificationResponse 

delete([options][, callback]) → Promise containing DeleteBucketResponse

Delete the bucket.

Examples

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');
bucket.delete(function(err, apiResponse) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.delete().then(function(data) {
  const apiResponse = data[0];
});

include:samples/buckets.js

region_tag:storage_delete_bucket
Another example:

Parameters

Name Type Optional Description

options

DeleteBucketOptions

Yes

Configuration options.

callback

DeleteBucketCallback

Yes

Callback function.

See also

Buckets: delete API Documentation

Returns

Promise containing DeleteBucketResponse 

deleteFiles([query][, callback]) → Promise

Iterate over the bucket's files, calling file.delete() on each.

This is not an atomic request. A delete attempt will be made for each file individually. Any one can fail, in which case only a portion of the files you intended to be deleted would have.

Operations are performed in parallel, up to 10 at once. The first error breaks the loop and will execute the provided callback with it. Specify { force: true } to suppress the errors until all files have had a chance to be processed.

The query object passed as the first argument will also be passed to Bucket#getFiles.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

//-
// Delete all of the files in the bucket.
//-
bucket.deleteFiles(function(err) {});

//-
// By default, if a file cannot be deleted, this method will stop deleting
// files from your bucket. You can override this setting with `force:
// true`.
//-
bucket.deleteFiles({
  force: true
}, function(errors) {
  // `errors`:
  //    Array of errors if any occurred, otherwise null.
});

//-
// The first argument to this method acts as a query to
// {@link Bucket#getFiles}. As an example, you can delete files
// which match a prefix.
//-
bucket.deleteFiles({
  prefix: 'images/'
}, function(err) {
  if (!err) {
    // All files in the `images` directory have been deleted.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.deleteFiles().then(function() {});

Parameters

Name Type Optional Description

query

DeleteFilesOptions

Yes

Query object. See Bucket#getFiles

callback

DeleteFilesCallback

Yes

Callback function.

See also

Objects: delete API Documentation

Returns

Promise 

deleteLabels(labels[, callback]) → Promise containing DeleteLabelsResponse

Delete one or more labels from this bucket.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

//-
// Delete all of the labels from this bucket.
//-
bucket.deleteLabels(function(err, apiResponse) {});

//-
// Delete a single label.
//-
bucket.deleteLabels('labelone', function(err, apiResponse) {});

//-
// Delete a specific set of labels.
//-
bucket.deleteLabels([
  'labelone',
  'labeltwo'
], function(err, apiResponse) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.deleteLabels().then(function(data) {
  const apiResponse = data[0];
});

Parameters

Name Type Optional Description

labels

(string or Array of string)

 

The labels to delete. If no labels are provided, all of the labels are removed.

callback

DeleteLabelsCallback

Yes

Callback function.

Returns

Promise containing DeleteLabelsResponse 

disableRequesterPays([callback]) → Promise containing DisableRequesterPaysCallback

Early Access Testers Only

This feature is not yet widely-available.

Disable requesterPays functionality from this bucket.

Examples

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

bucket.disableRequesterPays(function(err, apiResponse) {
  if (!err) {
    // requesterPays functionality disabled successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.disableRequesterPays().then(function(data) {
  const apiResponse = data[0];
});

include:samples/requesterPays.js

region_tag:storage_disable_requester_pays
Example of disabling requester pays:

Parameter

Name Type Optional Description

callback

DisableRequesterPaysCallback

Yes

Callback function.

Returns

Promise containing DisableRequesterPaysCallback 

enableRequesterPays([callback]) → Promise containing EnableRequesterPaysResponse

Early Access Testers Only

This feature is not yet widely-available.

Enable requesterPays functionality for this bucket. This enables you, the bucket owner, to have the requesting user assume the charges for the access to your bucket and its contents.

Examples

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

bucket.enableRequesterPays(function(err, apiResponse) {
  if (!err) {
    // requesterPays functionality enabled successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.enableRequesterPays().then(function(data) {
  const apiResponse = data[0];
});

include:samples/requesterPays.js

region_tag:storage_enable_requester_pays
Example of enabling requester pays:

Parameter

Name Type Optional Description

callback

EnableRequesterPaysCallback

Yes

Callback function.

Returns

Promise containing EnableRequesterPaysResponse 

exists([options][, callback]) → Promise containing BucketExistsResponse

Check if the bucket exists.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

bucket.exists(function(err, exists) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.exists().then(function(data) {
  const exists = data[0];
});

Parameters

Name Type Optional Description

options

BucketExistsOptions

Yes

Configuration options.

callback

BucketExistsCallback

Yes

Callback function.

Returns

Promise containing BucketExistsResponse 

file(name[, options]) → File

Create a File object. See File to see how to handle the different use cases you may have.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');
const file = bucket.file('my-existing-file.png');

Parameters

Name Type Optional Description

name

string

 

The name of the file in this bucket.

options

object

Yes

Configuration options.

Values in options have the following properties:

Name Type Optional Description

generation

(string or number)

Yes

Only use a specific revision of this file.

encryptionKey

string

Yes

A custom encryption key. See Customer-supplied Encryption Keys.

kmsKeyName

string

Yes

The name of the Cloud KMS key that will be used to encrypt the object. Must be in the format: projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key. KMS key ring must use the same location as the bucket.

Returns

File 

get([options][, callback]) → Promise containing GetBucketResponse

Get a bucket if it exists.

You may optionally use this to "get or create" an object by providing an object with autoCreate set to true. Any extra configuration that is normally required for the create method must be contained within this object as well.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

bucket.get(function(err, bucket, apiResponse) {
  // `bucket.metadata` has been populated.
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.get().then(function(data) {
  const bucket = data[0];
  const apiResponse = data[1];
});

Parameters

Name Type Optional Description

options

GetBucketOptions

Yes

Configuration options.

callback

GetBucketCallback

Yes

Callback function.

Returns

Promise containing GetBucketResponse 

getFiles([query][, callback]) → Promise containing GetFilesResponse

Get File objects for the files currently in the bucket.

Examples

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

bucket.getFiles(function(err, files) {
  if (!err) {
    // files is an array of File objects.
  }
});

//-
// If your bucket has versioning enabled, you can get all of your files
// scoped to their generation.
//-
bucket.getFiles({
  versions: true
}, function(err, files) {
  // Each file is scoped to its generation.
});

//-
// To control how many API requests are made and page through the results
// manually, set `autoPaginate` to `false`.
//-
const callback = function(err, files, nextQuery, apiResponse) {
  if (nextQuery) {
    // More results exist.
    bucket.getFiles(nextQuery, callback);
  }

  // The `metadata` property is populated for you with the metadata at the
  // time of fetching.
  files[0].metadata;

  // However, in cases where you are concerned the metadata could have
  // changed, use the `getMetadata` method.
  files[0].getMetadata(function(err, metadata) {});
};

bucket.getFiles({
  autoPaginate: false
}, callback);

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.getFiles().then(function(data) {
  const files = data[0];
});

include:samples/files.js

region_tag:storage_list_files
Another example:

include:samples/files.js

region_tag:storage_list_files_with_prefix
Example of listing files, filtered by a prefix:

Parameters

Name Type Optional Description

query

GetFilesOptions

Yes

Query object for listing files.

callback

GetFilesCallback

Yes

Callback function.

See also

Objects: list API Documentation

Returns

Promise containing GetFilesResponse 

getLabels([options][, callback]) → Promise containing GetLabelsCallback

Get the labels currently set on this bucket.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

bucket.getLabels(function(err, labels) {
  if (err) {
    // Error handling omitted.
  }

  // labels = {
  //   label: 'labelValue',
  //   ...
  // }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.getLabels().then(function(data) {
  const labels = data[0];
});

Parameters

Name Type Optional Description

options

object

Yes

Configuration options.

Values in options have the following properties:

Name Type Optional Description

userProject

string

Yes

The ID of the project which will be billed for the request.

callback

GetLabelsCallback

Yes

Callback function.

Returns

Promise containing GetLabelsCallback 

getMetadata([options][, callback]) → Promise containing GetBucketMetadataResponse

Get the bucket's metadata.

To set metadata, see Bucket#setMetadata.

Examples

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

bucket.getMetadata(function(err, metadata, apiResponse) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.getMetadata().then(function(data) {
  const metadata = data[0];
  const apiResponse = data[1];
});

include:samples/requesterPays.js

region_tag:storage_get_requester_pays_status
Example of retrieving the requester pays status of a bucket:

Parameters

Name Type Optional Description

options

GetBucketMetadataOptions

Yes

Configuration options.

callback

GetBucketMetadataCallback

Yes

Callback function.

See also

Buckets: get API Documentation

Returns

Promise containing GetBucketMetadataResponse 

getNotifications([options][, callback]) → Promise containing GetNotificationsResponse

Retrieves a list of notification subscriptions for a given bucket.

Examples

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('my-bucket');

bucket.getNotifications(function(err, notifications, apiResponse) {
  if (!err) {
    // notifications is an array of Notification objects.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.getNotifications().then(function(data) {
  const notifications = data[0];
  const apiResponse = data[1];
});

include:samples/notifications.js

region_tag:storage_list_notifications
Another example:

Parameters

Name Type Optional Description

options

GetNotificationsOptions

Yes

Configuration options.

callback

GetNotificationsCallback

Yes

Callback function.

See also

Notifications: list

Returns

Promise containing GetNotificationsResponse 

lock(metageneration[, callback]) → Promise containing BucketLockResponse

Lock a previously-defined retention policy. This will prevent changes to the policy.

Example

const storage = require('@google-cloud/storage')();
const bucket = storage.bucket('albums');

const metageneration = 2;

bucket.lock(metageneration, function(err, apiResponse) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.lock(metageneration).then(function(data) {
  const apiResponse = data[0];
});

Parameters

Name Type Optional Description

metageneration

(Number or String)

 

The bucket's metageneration. This is accesssible from calling File#getMetadata.

callback

BucketLockCallback

Yes

Callback function.

Throws

Error 

if a metageneration is not provided.

Returns

Promise containing BucketLockResponse 

makePrivate([options][, callback]) → Promise containing MakeBucketPrivateResponse

Make the bucket listing private.

You may also choose to make the contents of the bucket private by specifying includeFiles: true. This will automatically run File#makePrivate for every file in the bucket.

When specifying includeFiles: true, use force: true to delay execution of your callback until all files have been processed. By default, the callback is executed after the first error. Use force to queue such errors until all files have been processed, after which they will be returned as an array as the first argument to your callback.

NOTE: This may cause the process to be long-running and use a high number of requests. Use with caution.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

//-
// Make the bucket private.
//-
bucket.makePrivate(function(err) {});

//-
// Make the bucket and its contents private.
//-
const opts = {
  includeFiles: true
};

bucket.makePrivate(opts, function(err, files) {
  // `err`:
  //    The first error to occur, otherwise null.
  //
  // `files`:
  //    Array of files successfully made private in the bucket.
});

//-
// Make the bucket and its contents private, using force to suppress errors
// until all files have been processed.
//-
const opts = {
  includeFiles: true,
  force: true
};

bucket.makePrivate(opts, function(errors, files) {
  // `errors`:
  //    Array of errors if any occurred, otherwise null.
  //
  // `files`:
  //    Array of files successfully made private in the bucket.
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.makePrivate(opts).then(function(data) {
  const files = data[0];
});

Parameters

Name Type Optional Description

options

MakeBucketPrivateOptions

Yes

Configuration options.

callback

MakeBucketPrivateCallback

Yes

Callback function.

See also

Buckets: patch API Documentation

Returns

Promise containing MakeBucketPrivateResponse 

makePublic([options][, callback]) → Promise containing MakeBucketPublicResponse

Make the bucket publicly readable.

You may also choose to make the contents of the bucket publicly readable by specifying includeFiles: true. This will automatically run File#makePublic for every file in the bucket.

When specifying includeFiles: true, use force: true to delay execution of your callback until all files have been processed. By default, the callback is executed after the first error. Use force to queue such errors until all files have been processed, after which they will be returned as an array as the first argument to your callback.

NOTE: This may cause the process to be long-running and use a high number of requests. Use with caution.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

//-
// Make the bucket publicly readable.
//-
bucket.makePublic(function(err) {});

//-
// Make the bucket and its contents publicly readable.
//-
const opts = {
  includeFiles: true
};

bucket.makePublic(opts, function(err, files) {
  // `err`:
  //    The first error to occur, otherwise null.
  //
  // `files`:
  //    Array of files successfully made public in the bucket.
});

//-
// Make the bucket and its contents publicly readable, using force to
// suppress errors until all files have been processed.
//-
const opts = {
  includeFiles: true,
  force: true
};

bucket.makePublic(opts, function(errors, files) {
  // `errors`:
  //    Array of errors if any occurred, otherwise null.
  //
  // `files`:
  //    Array of files successfully made public in the bucket.
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.makePublic(opts).then(function(data) {
  const files = data[0];
});

Parameters

Name Type Optional Description

options

MakeBucketPublicOptions

Yes

Configuration options.

callback

MakeBucketPublicCallback

Yes

Callback function.

See also

Buckets: patch API Documentation

Returns

Promise containing MakeBucketPublicResponse 

notification(id) → Notification

Get a reference to a Cloud Pub/Sub Notification.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('my-bucket');
const notification = bucket.notification('1');

Parameter

Name Type Optional Description

id

string

 

ID of notification.

See also
Notification
Returns

Notification 

removeRetentionPeriod([callback]) → Promise containing SetBucketMetadataResponse

Remove an already-existing retention policy from this bucket, if it is not locked.

Example

const storage = require('@google-cloud/storage')();
const bucket = storage.bucket('albums');

bucket.removeRetentionPeriod(function(err, apiResponse) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.removeRetentionPeriod().then(function(data) {
  const apiResponse = data[0];
});

Parameter

Name Type Optional Description

callback

SetBucketMetadataCallback

Yes

Callback function.

Returns

Promise containing SetBucketMetadataResponse 

setLabels(labels[, options][, callback]) → Promise containing SetLabelsResponse

Set labels on the bucket.

This makes an underlying call to Bucket#setMetadata, which is a PATCH request. This means an individual label can be overwritten, but unmentioned labels will not be touched.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

const labels = {
  labelone: 'labelonevalue',
  labeltwo: 'labeltwovalue'
};

bucket.setLabels(labels, function(err, metadata) {
  if (!err) {
    // Labels set successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.setLabels(labels).then(function(data) {
  const metadata = data[0];
});

Parameters

Name Type Optional Description

labels

Object with string properties

 

Labels to set on the bucket.

options

object

Yes

Configuration options.

callback

SetLabelsCallback

Yes

Callback function.

Returns

Promise containing SetLabelsResponse 

setMetadata(metadata[, options][, callback]) → Promise containing SetBucketMetadataResponse

Set the bucket's metadata.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

//-
// Set website metadata field on the bucket.
//-
const metadata = {
  website: {
    mainPageSuffix: 'http://example.com',
    notFoundPage: 'http://example.com/404.html'
  }
};

bucket.setMetadata(metadata, function(err, apiResponse) {});

//-
// Enable versioning for your bucket.
//-
bucket.setMetadata({
  versioning: {
    enabled: true
  }
}, function(err, apiResponse) {});

//-
// Enable KMS encryption for objects within this bucket.
//-
bucket.setMetadata({
  encryption: {
    defaultKmsKeyName: 'projects/grape-spaceship-123/...'
  }
}, function(err, apiResponse) {});

//-
// Set the default event-based hold value for new objects in this
// bucket.
//-
bucket.setMetadata({
  defaultEventBasedHold: true
}, function(err, apiResponse) {});

//-
// Remove object lifecycle rules.
//-
bucket.setMetadata({
  lifecycle: null
}, function(err, apiResponse) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.setMetadata(metadata).then(function(data) {
  const apiResponse = data[0];
});

Parameters

Name Type Optional Description

metadata

Object with any type properties

 

The metadata you wish to set.

options

SetBucketMetadataOptions

Yes

Configuration options.

callback

SetBucketMetadataCallback

Yes

Callback function.

See also

Buckets: patch API Documentation

Returns

Promise containing SetBucketMetadataResponse 

setRetentionPeriod(duration[, callback]) → Promise containing SetBucketMetadataResponse

Lock all objects contained in the bucket, based on their creation time. Any attempt to overwrite or delete objects younger than the retention period will result in a PERMISSION_DENIED error.

An unlocked retention policy can be modified or removed from the bucket via File#removeRetentionPeriod and File#setRetentionPeriod. A locked retention policy cannot be removed or shortened in duration for the lifetime of the bucket. Attempting to remove or decrease period of a locked retention policy will result in a PERMISSION_DENIED error. You can still increase the policy.

Example

const storage = require('@google-cloud/storage')();
const bucket = storage.bucket('albums');

const DURATION_SECONDS = 15780000; // 6 months.

//-
// Lock the objects in this bucket for 6 months.
//-
bucket.setRetentionPeriod(DURATION_SECONDS, function(err, apiResponse) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.setRetentionPeriod(DURATION_SECONDS).then(function(data) {
  const apiResponse = data[0];
});

Parameters

Name Type Optional Description

duration

any type

 

In seconds, the minimum retention time for all objects contained in this bucket.

callback

SetBucketMetadataCallback

Yes

Callback function.

Returns

Promise containing SetBucketMetadataResponse 

setStorageClass(storageClass[, options][, callback]) → Promise

Set the default storage class for new files in this bucket.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

bucket.setStorageClass('regional', function(err, apiResponse) {
  if (err) {
    // Error handling omitted.
  }

  // The storage class was updated successfully.
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.setStorageClass('regional').then(function() {});

Parameters

Name Type Optional Description

storageClass

string

 

The new storage class. (standard, nearline, coldline, or durable_reduced_availability). Note: The legacy storage classes multi_regional and regional have been deprecated.

options

object

Yes

Configuration options.

Values in options have the following properties:

Name Type Optional Description

userProject

string

Yes

The ID of the project which will be billed for the request.

callback

SetStorageClassCallback

Yes

Callback function.

See also

Storage Classes

Returns

Promise 

setUserProject(userProject)

Set a user project to be billed for all requests made from this Bucket object and any files referenced from this Bucket object.

Example

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

bucket.setUserProject('grape-spaceship-123');

Parameter

Name Type Optional Description

userProject

string

 

The user project.

upload(pathString[, options][, callback]) → Promise containing UploadResponse

Upload a file to the bucket. This is a convenience method that wraps File#createWriteStream.

You can specify whether or not an upload is resumable by setting options.resumable. Resumable uploads are enabled by default if your input file is larger than 5 MB.

For faster crc32c computation, you must manually install fast-crc32c:

$ npm install --save fast-crc32c

Examples

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('albums');

//-
// Upload a file from a local path.
//-
bucket.upload('/local/path/image.png', function(err, file, apiResponse) {
  // Your bucket now contains:
  // - "image.png" (with the contents of `/local/path/image.png')

  // `file` is an instance of a File object that refers to your new file.
});


//-
// It's not always that easy. You will likely want to specify the filename
// used when your new file lands in your bucket.
//
// You may also want to set metadata or customize other options.
//-
const options = {
  destination: 'new-image.png',
  resumable: true,
  validation: 'crc32c',
  metadata: {
    metadata: {
      event: 'Fall trip to the zoo'
    }
  }
};

bucket.upload('local-image.png', options, function(err, file) {
  // Your bucket now contains:
  // - "new-image.png" (with the contents of `local-image.png')

  // `file` is an instance of a File object that refers to your new file.
});

//-
// You can also have a file gzip'd on the fly.
//-
bucket.upload('index.html', { gzip: true }, function(err, file) {
  // Your bucket now contains:
  // - "index.html" (automatically compressed with gzip)

  // Downloading the file with `file.download` will automatically decode
the
  // file.
});

//-
// You may also re-use a File object, {File}, that references
// the file you wish to create or overwrite.
//-
const options = {
  destination: bucket.file('existing-file.png'),
  resumable: false
};

bucket.upload('local-img.png', options, function(err, newFile) {
  // Your bucket now contains:
  // - "existing-file.png" (with the contents of `local-img.png')

  // Note:
  // The `newFile` parameter is equal to `file`.
});

//-
// To use
// <a
href="https://cloud.google.com/storage/docs/encryption#customer-supplied">
// Customer-supplied Encryption Keys</a>, provide the `encryptionKey`
option.
//-
const crypto = require('crypto');
const encryptionKey = crypto.randomBytes(32);

bucket.upload('img.png', {
  encryptionKey: encryptionKey
}, function(err, newFile) {
  // `img.png` was uploaded with your custom encryption key.

  // `newFile` is already configured to use the encryption key when making
  // operations on the remote object.

  // However, to use your encryption key later, you must create a `File`
  // instance with the `key` supplied:
  const file = bucket.file('img.png', {
    encryptionKey: encryptionKey
  });

  // Or with `file#setEncryptionKey`:
  const file = bucket.file('img.png');
  file.setEncryptionKey(encryptionKey);
});

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.upload('local-image.png').then(function(data) {
  const file = data[0];
});

To upload a file from a URL, use {@link File#createWriteStream}.

include:samples/files.js

region_tag:storage_upload_file
Another example:

include:samples/encryption.js

region_tag:storage_upload_encrypted_file
Example of uploading an encrypted file:

Parameters

Name Type Optional Description

pathString

string

 

The fully qualified path to the file you wish to upload to your bucket.

options

UploadOptions

Yes

Configuration options.

callback

UploadCallback

Yes

Callback function.

See also

Upload Options (Simple or Resumable)

Objects: insert API Documentation

Returns

Promise containing UploadResponse