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

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

// 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';
// const userEmail = 'Email of user to check, e.g. developer@company.com';

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

// 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';
// const userEmail = 'Email of user to add, e.g. developer@company.com';

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

// 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';
// const userEmail = 'Email of user to remove, e.g. developer@company.com';

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

// 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';
// const userEmail = 'Email of user to add, e.g. developer@company.com';

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

// 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';
// const userEmail = 'Email of user to remove, e.g. developer@company.com';

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const roleName = 'Role to grant, e.g. roles/storage.objectViewer';
// const members = [
//   'user:jdoe@example.com',    // Example members to grant
//   'group:admins@example.com', // the new role to
// ];

// Creates a client
const storage = new 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');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const roleName = 'Role to grant, e.g. roles/storage.objectViewer';
// const members = [
//   'user:jdoe@example.com',    // Example members to grant
//   'group:admins@example.com', // the new role to
// ];

// Creates a client
const storage = new 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.

userProject

string

A user project to apply to each request from this bucket.

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

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.

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 CreateBucketResponse

Create a bucket.

Parameter

metadata

Optional

CreateBucketRequest

Metadata to set for the bucket.

callback

Optional

CreateBucketCallback

Callback function.

Returns

Promise containing 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

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

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

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

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

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

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

//-
// Configure the nofiication by providing Notification metadata.
//-
var 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) {
  var notification = data[0];
  var 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

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

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

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

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

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

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

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

string

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

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

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

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

string

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

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