Properties

acl

Cloud Storage uses access control lists (ACLs) to manage object and bucket access. ACLs are the mechanism you use to share objects with other users and allow other users to access your buckets and objects.

An ACL consists of one or more entries, where each entry grants permissions to an entity. Permissions define the actions that can be performed against an object or bucket (for example, READ or WRITE); the entity defines who the permission applies to (for example, a specific user or group of users).

The acl object on a Bucket instance provides methods to get you a list of the ACLs defined on your bucket, as well as set, update, and delete them.

Buckets also have default ACLs for all created files. Default ACLs specify permissions that all new objects added to the bucket will inherit by default. You can add, delete, get, and update entities and permissions for these as well with Bucket#acl.default.

Property

Parameter

default

Acl

Cloud Storage Buckets have default ACLs for all created files. You can add, delete, get, and update entities and permissions for these as well. The method signatures and examples are all the same, after only prefixing the method call with default.

Mixes in
Acl
See also

About Access Control Lists

Default ACLs

Example

var storage = require('@google-cloud/storage')();

//-
// Make a bucket's contents publicly readable.
//-
var myBucket = storage.bucket('my-bucket');

var options = {
  entity: 'allUsers',
  role: storage.acl.READER_ROLE
};

myBucket.acl.add(options, function(err, aclObject) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
myBucket.acl.add(options).then(function(data) {
  var aclObject = data[0];
  var apiResponse = data[1];
});

Example of printing a bucket's ACL:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// Instantiates a client
const storage = Storage();

// Gets the ACL for the bucket
storage
  .bucket(bucketName)
  .acl.get()
  .then(results => {
    const acls = results[0];

    acls.forEach(acl => {
      console.log(`${acl.role}: ${acl.entity}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Example of printing a bucket's ACL for a specific user:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The email of the user to check, e.g. "developer@company.com"
// const userEmail = "developer@company.com";

// Instantiates a client
const storage = Storage();

const options = {
  // Specify the user
  entity: `user-${userEmail}`,
};

// Gets the user's ACL for the bucket
storage
  .bucket(bucketName)
  .acl.get(options)
  .then(results => {
    const aclObject = results[0];

    console.log(`${aclObject.role}: ${aclObject.entity}`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Example of adding an owner to a bucket:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The email of the user to add, e.g. "developer@company.com"
// const userEmail = "developer@company.com";

// Instantiates a client
const storage = Storage();

// Makes the user an owner of the bucket. You can use addAllUsers(),
// addDomain(), addProject(), addGroup(), and addAllAuthenticatedUsers()
// to grant access to different types of entities. You can also use "readers"
// and "writers" to grant different roles.
storage
  .bucket(bucketName)
  .acl.owners.addUser(userEmail)
  .then(() => {
    console.log(
      `Added user ${userEmail} as an owner on bucket ${bucketName}.`
    );
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Example of removing an owner from a bucket:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The email of the user to remove, e.g. "developer@company.com"
// const userEmail = "developer@company.com";

// Instantiates a client
const storage = Storage();

// Removes the user from the access control list of the bucket. You can use
// deleteAllUsers(), deleteDomain(), deleteProject(), deleteGroup(), and
// deleteAllAuthenticatedUsers() to remove access for different types of entities.
storage
  .bucket(bucketName)
  .acl.owners.deleteUser(userEmail)
  .then(() => {
    console.log(`Removed user ${userEmail} from bucket ${bucketName}.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Example of adding a default owner to a bucket:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The email of the user to add, e.g. "developer@company.com"
// const userEmail = "developer@company.com";

// Instantiates a client
const storage = Storage();

// Makes the user an owner in the default ACL of the bucket. You can use
// addAllUsers(), addDomain(), addProject(), addGroup(), and
// addAllAuthenticatedUsers() to grant access to different types of entities.
// You can also use "readers" and "writers" to grant different roles.
storage
  .bucket(bucketName)
  .acl.default.owners.addUser(userEmail)
  .then(() => {
    console.log(
      `Added user ${userEmail} as an owner on bucket ${bucketName}.`
    );
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Example of removing a default owner from a bucket:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The email of the user to remove, e.g. "developer@company.com"
// const userEmail = "developer@company.com";

// Instantiates a client
const storage = Storage();

// Removes the user from the access control list of the bucket. You can use
// deleteAllUsers(), deleteDomain(), deleteProject(), deleteGroup(), and
// deleteAllAuthenticatedUsers() to remove access for different types of entities.
storage
  .bucket(bucketName)
  .acl.default.owners.deleteUser(userEmail)
  .then(() => {
    console.log(`Removed user ${userEmail} from bucket ${bucketName}.`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

iam

Get and set IAM policies for your bucket.

Mixes in
Iam
See also

Cloud Storage IAM Management

Granting, Changing, and Revoking Access

IAM Roles

Example

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

//-
// Get the IAM policy for your bucket.
//-
bucket.iam.getPolicy(function(err, policy) {
  console.log(policy);
});

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

Example of retrieving a bucket's IAM policy:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

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

// Gets and displays the bucket's IAM policy
storage
  .bucket(bucketName)
  .iam.getPolicy()
  .then(results => {
    const policy = results[0].bindings;

    // Displays the roles in the bucket's IAM policy
    console.log(`Roles for bucket ${bucketName}:`);
    policy.forEach(role => {
      console.log(`  Role: ${role.role}`);
      console.log(`  Members:`);

      const members = role.members;
      members.forEach(member => {
        console.log(`    ${member}`);
      });
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Example of adding to a bucket's IAM policy:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The bucket-level IAM role to grant, e.g. "roles/storage.objectViewer"
// const roleName = "roles/storage.objectViewer";

// The list of IAM members to grant the role to, e.g. ['user:jdoe@example.com', 'group:admins@example.com']
// const members = ['user:jdoe@example.com', 'group:admins@example.com'];

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

// Get a reference to a Google Cloud Storage bucket
const bucket = storage.bucket(bucketName);

// Gets and updates the bucket's IAM policy
bucket.iam
  .getPolicy()
  .then(results => {
    const policy = results[0];

    // Adds the new roles to the bucket's IAM policy
    policy.bindings.push({
      role: roleName,
      members: members,
    });

    // Updates the bucket's IAM policy
    return bucket.iam.setPolicy(policy);
  })
  .then(() => {
    console.log(
      `Added the following member(s) with role ${roleName} to ${bucketName}:`
    );
    members.forEach(member => {
      console.log(`  ${member}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Example of removing from a bucket's IAM policy:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The bucket-level IAM role to grant, e.g. "roles/storage.objectViewer"
// const roleName = "roles/storage.objectViewer";

// The list of IAM members to grant the role to, e.g. ['user:jdoe@example.com', 'group:admins@example.com']
// const members = ['user:jdoe@example.com', 'group:admins@example.com'];

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

// Get a reference to a Google Cloud Storage bucket
const bucket = storage.bucket(bucketName);

// Gets and updates the bucket's IAM policy
bucket.iam
  .getPolicy()
  .then(data => {
    const policy = data[0];

    // Finds and updates the appropriate role-member group
    const index = policy.bindings.findIndex(role => role.role === roleName);
    let role = policy.bindings[index];
    if (role) {
      role.members = role.members.filter(
        member => members.indexOf(member) === -1
      );

      // Updates the policy object with the new (or empty) role-member group
      if (role.members.length === 0) {
        policy.bindings.splice(index, 1);
      } else {
        policy.bindings.index = role;
      }

      // Updates the bucket's IAM policy
      return bucket.iam.setPolicy(policy);
    } else {
      // No matching role-member group(s) were found
      throw new Error('No matching role-member group(s) found.');
    }
  })
  .then(() => {
    console.log(
      `Removed the following member(s) with role ${roleName} from ${bucketName}:`
    );
    members.forEach(member => {
      console.log(`  ${member}`);
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

name

string

The bucket's name.

storage

string

A reference to the Storage associated with this Bucket instance.

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

userProject

Optional

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

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.

Error 

if content type can't be determined for the destination file.

Returns

Promise containing CombineResponse 

Example

var storage = require('@google-cloud/storage')();
var logBucket = storage.bucket('log-bucket');

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

var 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) {
  var newFile = data[0];
  var apiResponse = data[1];
});

create

create(metadata, callback) returns Promise containing Storage~CreateBucketResponse

Create a bucket.

Parameter

metadata

Optional

Storage~CreateBucketRequest

Metadata to set for the bucket.

callback

Optional

Storage~CreateBucketCallback

Callback function.

Returns

Promise containing Storage~CreateBucketResponse 

Example

var storage = require('@google-cloud/storage')();
var 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) {
  var bucket = data[0];
  var 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

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

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

var storage = require('@google-cloud/storage')();
var bucket = storage.bucket('albums');
var id = 'new-channel-id';

var 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) {
  var channel = data[0];
  var apiResponse = data[1];
});

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

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

callback

Optional

DeleteBucketCallback

Callback function.

See also

Buckets: delete API Documentation

Returns

Promise containing DeleteBucketResponse 

Example

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

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

Another example:

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

// The name of the bucket to delete, e.g. "my-bucket"
// const bucketName = "my-bucket";

// Instantiates a client
const storage = Storage();

// 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

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

callback

Optional

DeleteFilesCallback

Callback function.

See also

Objects: delete API Documentation

Returns

Promise 

Example

var storage = require('@google-cloud/storage')();
var 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

var storage = require('@google-cloud/storage')();
var 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) {
  var 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

var storage = require('@google-cloud/storage')();
var 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) {
  var apiResponse = data[0];
});

Example of disabling requester pays:

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

// The name of the bucket to disable requester-paying for, e.g. "my-bucket"
// const bucketName = "my-bucket";

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

// 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

var storage = require('@google-cloud/storage')();
var 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) {
  var apiResponse = data[0];
});

Example of enabling requester pays:

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

// The name of the bucket to enable requester-paying for, e.g. "my-bucket"
// const bucketName = "my-bucket";

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

// 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

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

callback

Optional

BucketExistsCallback

Callback function.

Returns

Promise containing BucketExistsResponse 

Example

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

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

//-
// If the callback is omitted, we'll return a Promise.
//-
bucket.exists().then(function(data) {
  var 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.

key

Optional

string

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

Returns

File 

Example

var storage = require('@google-cloud/storage')();
var bucket = storage.bucket('albums');
var 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

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

callback

Optional

GetBucketCallback

Callback function.

Returns

Promise containing GetBucketResponse 

Example

var storage = require('@google-cloud/storage')();
var 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) {
  var bucket = data[0];
  var 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

var storage = require('@google-cloud/storage')();
var 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`.
//-
var 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) {
  var files = data[0];
});

Another example:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// Instantiates a client
const storage = Storage();

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The prefix by which to filter files, e.g. "public/"
// const prefix = "public/";

// The delimiter to use, e.g. "/"
// const delimiter = "/";

// Instantiates a client
const storage = Storage();

/**
 * 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);
  });

getFilesStream

getFilesStream(query) returns ReadableStream

Get File objects for the files currently in the bucket as a readable object stream.

Parameter

query

Optional

GetFilesRequest

Query object for listing files.

Returns

ReadableStream 

A readable stream that emits File instances.

Example

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

bucket.getFilesStream()
  .on('error', console.error)
  .on('data', function(file) {
    // file is a File object.
  })
  .on('end', function() {
    // All files retrieved.
  });

//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
bucket.getFilesStream()
  .on('data', function(file) {
    this.end();
  });

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

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

callback

Optional

GetLabelsCallback

Callback function.

Returns

Promise containing GetLabelsCallback 

Example

var storage = require('@google-cloud/storage')();
var 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) {
  var 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

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

callback

Optional

GetBucketMetadataCallback

Callback function.

See also

Buckets: get API Documentation

Returns

Promise containing GetBucketMetadataResponse 

Example

var storage = require('@google-cloud/storage')();
var 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) {
  var metadata = data[0];
  var 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`);

// The name of the bucket to get the requester-payable status for, e.g. "my-bucket"
// const bucketName = "my-bucket";

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

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

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

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

callback

Optional

MakeBucketPrivateCallback

Callback function.

See also

Buckets: patch API Documentation

Returns

Promise containing MakeBucketPrivateResponse 

Example

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

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

//-
// Make the bucket and its contents private.
//-
var 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.
//-
var 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) {
  var 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

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

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

//-
// Make the bucket and its contents publicly readable.
//-
var 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.
//-
var 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) {
  var files = 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.

Values in options have the following properties:

Parameter

userProject

Optional

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

callback

Optional

SetLabelsCallback

Callback function.

Returns

Promise containing SetLabelsResponse 

Example

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

var 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) {
  var 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

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

callback

Optional

SetBucketMetadataCallback

Callback function.

See also

Buckets: patch API Documentation

Returns

Promise containing SetBucketMetadataResponse 

Example

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

//-
// Set website metadata field on the bucket.
//-
var 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) {});

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

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

callback

Optional

SetStorageClassCallback

Callback function.

See also

Storage Classes

Returns

Promise 

Example

var storage = require('@google-cloud/storage')();
var 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() {});

upload

upload(localPath, 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

localPath

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.

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

boolean

If this bucket has requesterPays functionality enabled (see Bucket#enableRequesterPays), set this value to the project which should be billed for this operation.

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

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

//-
// The easiest way to upload a file.
//-
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.
//-
var 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.
//-
var 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.
//-
var crypto = require('crypto');
var 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:
  var file = bucket.file('img.png', {
    encryptionKey: encryptionKey
  });

  // Or with `file#setEncryptionKey`:
  var 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) {
  var file = data[0];
});

Another example:

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

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The name of the local file to upload, e.g. "./local/path/to/file.txt"
// const filename = "./local/path/to/file.txt";

// Instantiates a client
const storage = Storage();

// Uploads a local file to the bucket
storage
  .bucket(bucketName)
  .upload(filename)
  .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');

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The name of the local file to upload, e.g. "./local/path/to/file.txt"
// const srcFilename = "./local/path/to/file.txt";

// The path to which the file should be uploaded, e.g. "file_encrypted.txt"
// const destFilename = "file.txt";

// Instantiates a client
const storage = Storage();

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, e.g. "my-secret-key"
  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);
  });