Methods

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

object

Configuration options.

Values in options have the following properties:

Parameter

kmsKeyName

Optional

string

Resource name of the Cloud KMS key, of the form projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key, that will be used to encrypt the object. Overwrites the object metadata's kms_key_name value, if any.

userProject

Optional

string

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

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

object

See a Objects: watchAll request body.

Values in config have the following properties:

Parameter

address

string

The address where notifications are delivered for this channel.

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

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

CreateNotificationRequest

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
storage
  .bucket(bucketName)
  .createNotification(topic)
  .then(() => {
    console.log('Notification subscription created.');
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

delete

delete(options, callback) returns Promise containing DeleteBucketResponse

Delete the 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

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
storage
  .bucket(bucketName)
  .delete()
  .then(() => {
    console.log(`Bucket ${bucketName} deleted.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

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

object

Query object. See Bucket#getFiles for all of the supported properties.

Values in query have the following properties:

Parameter

force

Optional

boolean

Suppress errors until all files have been processed.

userProject

Optional

string

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

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
storage
  .bucket(bucketName)
  .disableRequesterPays()
  .then(() => {
    console.log(
      `Requester-pays requests have been disabled for bucket ${bucketName}.`
    );
  })
  .catch(err => {
    console.error(`ERROR:`, err);
  });

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
storage
  .bucket(bucketName)
  .enableRequesterPays()
  .then(() => {
    console.log(
      `Requester-pays requests have been enabled for bucket ${bucketName}.`
    );
  })
  .catch(err => {
    console.error(`ERROR:`, err);
  });

exists

exists(options, callback) returns Promise containing BucketExistsResponse

Check if the bucket exists.

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

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

object

Configuration options.

Values in options have the following properties:

Parameter

autoCreate

Optional

boolean

Automatically create the object if it does not exist. Default: false

userProject

Optional

string

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

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

GetFilesRequest

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
storage
  .bucket(bucketName)
  .getFiles()
  .then(results => {
    const files = results[0];

    console.log('Files:');
    files.forEach(file => {
      console.log(file.name);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

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
storage
  .bucket(bucketName)
  .getFiles(options)
  .then(results => {
    const files = results[0];

    console.log('Files:');
    files.forEach(file => {
      console.log(file.name);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

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

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

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
storage
  .bucket(bucketName)
  .getMetadata()
  .then(data => {
    let status;
    const metadata = data[0];
    if (metadata && metadata.billing && metadata.billing.requesterPays) {
      status = `enabled`;
    } else {
      status = `disabled`;
    }
    console.log(
      `Requester-pays requests are ${status} for bucket ${bucketName}.`
    );
  })
  .catch(err => {
    console.error(`ERROR:`, err);
  });

getNotifications

getNotifications(options, callback) returns Promise containing GetNotificationsResponse

Retrieves a list of notification subscriptions for a given 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

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
storage
  .bucket(bucketName)
  .getNotifications()
  .then(results => {
    const notifications = results[0];

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

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

object

Configuration options.

Values in options have the following properties:

Parameter

includeFiles

Optional

boolean

Make each file in the bucket private.

force

Optional

boolean

Queue errors occurred while making files private until all files have been processed.

userProject

Optional

string

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

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

object

Configuration options.

Values in options have the following properties:

Parameter

includeFiles

Optional

boolean

Make each file in the bucket publicly readable.

force

Optional

boolean

Queue errors occurred while making files public until all files have been processed.

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');

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.

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

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

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

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

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.setMetadata(metadata).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

object

Configuration options.

Values in options have the following properties:

Parameter

destination

Optional

(string or File)

The place to save your file. If given a string, the file will be uploaded to the bucket using the string as a filename. When given a File object, your local file will be uploaded to the File object's bucket and under the File object's name. Lastly, when this argument is omitted, the file is uploaded to your bucket using the name of the local file.

encryptionKey

Optional

string

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

gzip

Optional

boolean

Automatically gzip the file. This will set options.metadata.contentEncoding to gzip.

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.

metadata

Optional

object

See an Objects: insert request body.

offset

Optional

string

The starting byte of the upload stream, for resuming an interrupted upload. Defaults to 0.

predefinedAcl

Optional

string

Apply a predefined set of access controls to this object.

Acceptable values are:
- authenticatedRead - Object owner gets OWNER access, and
  allAuthenticatedUsers get READER access.

- bucketOwnerFullControl - Object owner gets OWNER access, and
  project team owners get OWNER access.

- bucketOwnerRead - Object owner gets OWNER access, and project
  team owners get READER access.

- private - Object owner gets OWNER access.

- projectPrivate - Object owner gets OWNER access, and project
  team members get access according to their roles.

- publicRead - Object owner gets OWNER access, and allUsers

get READER access.

private

Optional

boolean

Make the uploaded file private. (Alias for options.predefinedAcl = 'private')

public

Optional

boolean

Make the uploaded file public. (Alias for options.predefinedAcl = 'publicRead')

resumable

Optional

boolean

Force a resumable upload. (default: true for files larger than 5 MB).

uri

Optional

string

The URI for an already-created resumable upload. See File#createResumableUpload.

userProject

Optional

string

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

validation

Optional

(string or boolean)

Possible values: "md5", "crc32c", or false. By default, data integrity is validated with an MD5 checksum for maximum reliability. CRC32c will provide better performance with less reliability. You may also choose to skip validation completely, however this is not recommended.

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
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',
    },
  })
  .then(() => {
    console.log(`${filename} uploaded to ${bucketName}.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

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.
storage
  .bucket(bucketName)
  .upload(srcFilename, options)
  .then(() => {
    console.log(
      `File ${srcFilename} uploaded to gs://${bucketName}/${destFilename}.`
    );
  })
  .catch(err => {
    console.error('ERROR:', err);
  });