Methods

addLifecycleRule

addLifecycleRule(rule, options, callback) returns 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.

Parameter

rule

LifecycleRule

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

Values in rule have the following properties:

Parameter

storageClass

Optional

string

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

options

Optional

AddLifecycleRuleOptions

Configuration object.

Values in options have the following properties:

Parameter

append

Optional

boolean

Append the new rule to the existing policy.

callback

Optional

SetBucketMetadataCallback

Callback function.

See also

Object Lifecycle Management

Buckets: patch API Documentation

Returns

Promise containing SetBucketMetadataResponse 

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) {});

combine

combine(sources, destination, options, callback) returns Promise containing CombineResponse

Combine multiple files into one new file.

Parameter

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

Optional

CombineOptions

Configuration options.

callback

Optional

CombineCallback

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 

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];
});

create

create(metadata, callback) returns Promise containing CreateBucketResponse

Create a bucket.

Parameter

metadata

Optional

CreateBucketRequest

Metadata to set for the bucket.

callback

Optional

CreateBucketCallback

Callback function.

Returns

Promise containing CreateBucketResponse 

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];
});

createChannel

createChannel(id, config, options, callback) returns Promise containing CreateChannelResponse

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

Parameter

id

string

The ID of the channel to create.

config

CreateChannelConfig

Configuration for creating channel.

options

Optional

CreateChannelOptions

Configuration options.

callback

Optional

CreateChannelCallback

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 

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];
});

createNotification

createNotification(topic, options, callback) returns Promise containing CreateNotificationResponse

Creates a notification subscription for the bucket.

Parameter

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

Optional

CreateNotificationOptions

Metadata to set for the notification.

callback

Optional

CreateNotificationCallback

Callback function.

See also

Notifications: insert

Notification#create
Throws

Error 

If a valid topic is not provided.

Returns

Promise containing CreateNotificationResponse 

Example

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];
});

Another example:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const topic = 'Name of a topic, e.g. my-topic';

// Creates a notification
await storage.bucket(bucketName).createNotification(topic);

console.log('Notification subscription created.');

delete

delete(options, callback) returns Promise containing DeleteBucketResponse

Delete the bucket.

Parameter

options

Optional

DeleteBucketOptions

Configuration options.

callback

Optional

DeleteBucketCallback

Callback function.

See also

Buckets: delete API Documentation

Returns

Promise containing DeleteBucketResponse 

Example

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];
});

Another example:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Deletes the bucket
await storage.bucket(bucketName).delete();

console.log(`Bucket ${bucketName} deleted.`);

deleteFiles

deleteFiles(query, callback) returns 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.

Parameter

query

Optional

DeleteFilesOptions

Query object. See Bucket#getFiles

callback

Optional

DeleteFilesCallback

Callback function.

See also

Objects: delete API Documentation

Returns

Promise 

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() {});

deleteLabels

deleteLabels(labels, callback) returns Promise containing DeleteLabelsResponse

Delete one or more labels from this bucket.

Parameter

labels

(string or Array of string)

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

callback

Optional

DeleteLabelsCallback

Callback function.

Returns

Promise containing DeleteLabelsResponse 

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];
});

disableRequesterPays

disableRequesterPays(callback) returns Promise containing DisableRequesterPaysCallback

Early Access Testers Only

This feature is not yet widely-available.

Disable requesterPays functionality from this bucket.

Parameter

callback

Optional

DisableRequesterPaysCallback

Callback function.

Returns

Promise containing DisableRequesterPaysCallback 

Example

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];
});

Example of disabling requester pays:

// Imports the Google Cloud client library
const {Storage} = require(`@google-cloud/storage`);

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Disables requester-pays requests
await storage.bucket(bucketName).disableRequesterPays();

console.log(
  `Requester-pays requests have been disabled for bucket ${bucketName}.`
);

enableRequesterPays

enableRequesterPays(callback) returns 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.

Parameter

callback

Optional

EnableRequesterPaysCallback

Callback function.

Returns

Promise containing EnableRequesterPaysResponse 

Example

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];
});

Example of enabling requester pays:

// Imports the Google Cloud client library
const {Storage} = require(`@google-cloud/storage`);

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Enables requester-pays requests
await storage.bucket(bucketName).enableRequesterPays();

console.log(
  `Requester-pays requests have been enabled for bucket ${bucketName}.`
);

exists

exists(options, callback) returns Promise containing BucketExistsResponse

Check if the bucket exists.

Parameter

options

Optional

BucketExistsOptions

Configuration options.

callback

Optional

BucketExistsCallback

Callback function.

Returns

Promise containing BucketExistsResponse 

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];
});

file

file(name, options) returns File

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

Parameter

name

string

The name of the file in this bucket.

options

Optional

object

Configuration options.

Values in options have the following properties:

Parameter

generation

Optional

(string or number)

Only use a specific revision of this file.

encryptionKey

Optional

string

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

kmsKeyName

Optional

string

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 

Example

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

get

get(options, callback) returns 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.

Parameter

options

Optional

GetBucketOptions

Configuration options.

callback

Optional

GetBucketCallback

Callback function.

Returns

Promise containing GetBucketResponse 

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];
});

getFiles

getFiles(query, callback) returns Promise containing GetFilesResponse

Get File objects for the files currently in the bucket.

Parameter

query

Optional

GetFilesOptions

Query object for listing files.

callback

Optional

GetFilesCallback

Callback function.

See also

Objects: list API Documentation

Returns

Promise containing GetFilesResponse 

Example

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];
});

Another example:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Lists files in the bucket
const [files] = await storage.bucket(bucketName).getFiles();

console.log('Files:');
files.forEach(file => {
  console.log(file.name);
});

Example of listing files, filtered by a prefix:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const prefix = 'Prefix by which to filter, e.g. public/';
// const delimiter = 'Delimiter to use, e.g. /';

/**
 * This can be used to list all blobs in a "folder", e.g. "public/".
 *
 * The delimiter argument can be used to restrict the results to only the
 * "files" in the given "folder". Without the delimiter, the entire tree under
 * the prefix is returned. For example, given these blobs:
 *
 *   /a/1.txt
 *   /a/b/2.txt
 *
 * If you just specify prefix = '/a', you'll get back:
 *
 *   /a/1.txt
 *   /a/b/2.txt
 *
 * However, if you specify prefix='/a' and delimiter='/', you'll get back:
 *
 *   /a/1.txt
 */
const options = {
  prefix: prefix,
};

if (delimiter) {
  options.delimiter = delimiter;
}

// Lists files in the bucket, filtered by a prefix
const [files] = await storage.bucket(bucketName).getFiles(options);

console.log('Files:');
files.forEach(file => {
  console.log(file.name);
});

getLabels

getLabels(options, callback) returns Promise containing GetLabelsCallback

Get the labels currently set on this bucket.

Parameter

options

Optional

object

Configuration options.

Values in options have the following properties:

Parameter

userProject

Optional

string

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

callback

Optional

GetLabelsCallback

Callback function.

Returns

Promise containing GetLabelsCallback 

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];
});

getMetadata

getMetadata(options, callback) returns Promise containing GetBucketMetadataResponse

Get the bucket's metadata.

To set metadata, see Bucket#setMetadata.

Parameter

options

Optional

GetBucketMetadataOptions

Configuration options.

callback

Optional

GetBucketMetadataCallback

Callback function.

See also

Buckets: get API Documentation

Returns

Promise containing GetBucketMetadataResponse 

Example

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];
});

Example of retrieving the requester pays status of a bucket:

// Imports the Google Cloud client library
const {Storage} = require(`@google-cloud/storage`);

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Gets the requester-pays status of a bucket
const [metadata] = await storage.bucket(bucketName).getMetadata();

let status;
if (metadata && metadata.billing && metadata.billing.requesterPays) {
  status = `enabled`;
} else {
  status = `disabled`;
}
console.log(
  `Requester-pays requests are ${status} for bucket ${bucketName}.`
);

getNotifications

getNotifications(options, callback) returns Promise containing GetNotificationsResponse

Retrieves a list of notification subscriptions for a given bucket.

Parameter

options

Optional

GetNotificationsOptions

Configuration options.

callback

Optional

GetNotificationsCallback

Callback function.

See also

Notifications: list

Returns

Promise containing GetNotificationsResponse 

Example

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];
});

Another example:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Lists notifications in the bucket
const [notifications] = await storage.bucket(bucketName).getNotifications();

console.log('Notifications:');
notifications.forEach(notification => {
  console.log(notification.id);
});

lock

lock(metageneration, callback) returns Promise containing BucketLockResponse

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

Parameter

metageneration

(Number or String)

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

callback

Optional

BucketLockCallback

Callback function.

Throws

Error 

if a metageneration is not provided.

Returns

Promise containing BucketLockResponse 

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];
});

makePrivate

makePrivate(options, callback) returns 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.

Parameter

options

Optional

MakeBucketPrivateOptions

Configuration options.

callback

Optional

MakeBucketPrivateCallback

Callback function.

See also

Buckets: patch API Documentation

Returns

Promise containing MakeBucketPrivateResponse 

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];
});

makePublic

makePublic(options, callback) returns 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.

Parameter

options

Optional

MakeBucketPublicOptions

Configuration options.

callback

Optional

MakeBucketPublicCallback

Callback function.

See also

Buckets: patch API Documentation

Returns

Promise containing MakeBucketPublicResponse 

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];
});

notification

notification(id) returns Notification

Get a reference to a Cloud Pub/Sub Notification.

Parameter

id

string

ID of notification.

See also
Notification
Returns

Notification 

Example

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

removeRetentionPeriod

removeRetentionPeriod(callback) returns Promise containing SetBucketMetadataResponse

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

Parameter

callback

Optional

SetBucketMetadataCallback

Callback function.

Returns

Promise containing SetBucketMetadataResponse 

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];
});

setLabels

setLabels(labels, options, callback) returns 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.

Parameter

labels

Object with string properties

Labels to set on the bucket.

options

Optional

object

Configuration options.

callback

Optional

SetLabelsCallback

Callback function.

Returns

Promise containing SetLabelsResponse 

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];
});

setMetadata

setMetadata(metadata, options, callback) returns Promise containing SetBucketMetadataResponse

Set the bucket's metadata.

Parameter

metadata

Object with any type properties

The metadata you wish to set.

options

Optional

SetBucketMetadataOptions

Configuration options.

callback

Optional

SetBucketMetadataCallback

Callback function.

See also

Buckets: patch API Documentation

Returns

Promise containing SetBucketMetadataResponse 

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];
});

setRetentionPeriod

setRetentionPeriod(duration, callback) returns 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.

Parameter

duration

any type

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

callback

Optional

SetBucketMetadataCallback

Callback function.

Returns

Promise containing SetBucketMetadataResponse 

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];
});

setStorageClass

setStorageClass(storageClass, options, callback) returns Promise

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

Parameter

storageClass

string

The new storage class. (multi_regional, regional, standard, nearline, coldline, or durable_reduced_availability)

options

Optional

object

Configuration options.

Values in options have the following properties:

Parameter

userProject

Optional

string

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

callback

Optional

SetStorageClassCallback

Callback function.

See also

Storage Classes

Returns

Promise 

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() {});

setUserProject

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.

Parameter

userProject

string

The user project.

Example

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

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

upload

upload(pathString, options, callback) returns 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

Parameter

pathString

string

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

options

Optional

UploadOptions

Configuration options.

callback

Optional

UploadCallback

Callback function.

See also

Upload Options (Simple or Resumable)

Objects: insert API Documentation

Returns

Promise containing UploadResponse 

Example

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}.

Another example:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'Local file to upload, e.g. ./local/path/to/file.txt';

// Uploads a local file to the bucket
await storage.bucket(bucketName).upload(filename, {
  // Support for HTTP requests made with `Accept-Encoding: gzip`
  gzip: true,
  metadata: {
    // Enable long-lived HTTP caching headers
    // Use only if the contents of the file will never change
    // (If the contents will change, use cacheControl: 'no-cache')
    cacheControl: 'public, max-age=31536000',
  },
});

console.log(`${filename} uploaded to ${bucketName}.`);

Example of uploading an encrypted file:

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const srcFilename = 'Local file to upload, e.g. ./local/path/to/file.txt';
// const destFilename = 'Remote destination for file, e.g. file_encrypted.txt';

// See the "Generating your own encryption key" section above.
// const key = 'A base64 encoded customer-supplied key';

const options = {
  // The path to which the file should be uploaded, e.g. "file_encrypted.txt"
  destination: destFilename,
  // Encrypt the file with a customer-supplied key.
  // See the "Generating your own encryption key" section above.
  encryptionKey: Buffer.from(key, 'base64'),
};

// Encrypts and uploads a local file, e.g. "./local/path/to/file.txt".
// The file will only be retrievable using the key used to upload it.
await storage.bucket(bucketName).upload(srcFilename, options);

console.log(
  `File ${srcFilename} uploaded to gs://${bucketName}/${destFilename}.`
);