Constructor
new Storage(optionsopt)
Constructs the Storage client.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
options |
StorageOptions |
<optional> |
Configuration options. |
Examples
Create a client that uses Application Default Credentials
(ADC)
```
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
```
Create a client with explicit credentials
```
const storage = new Storage({
projectId: 'your-project-id',
keyFilename: '/path/to/keyfile.json'
});
```
Create a client with credentials passed
by value as a JavaScript object
```
const storage = new Storage({
projectId: 'your-project-id',
credentials: {
type: 'service_account',
project_id: 'xxxxxxx',
private_key_id: 'xxxx',
private_key:'-----BEGIN PRIVATE KEY-----xxxxxxx\n-----END PRIVATE KEY-----\n',
client_email: 'xxxx',
client_id: 'xxx',
auth_uri: 'https://accounts.google.com/o/oauth2/auth',
token_uri: 'https://oauth2.googleapis.com/token',
auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs',
client_x509_cert_url: 'xxx',
}
});
```
Create a client with credentials passed
by loading a JSON file directly from disk
```
const storage = new Storage({
projectId: 'your-project-id',
credentials: require('/path/to-keyfile.json')
});
```
Create a client with an `AuthClient` (e.g. `DownscopedClient`)
```
const {DownscopedClient} = require('google-auth-library');
const authClient = new DownscopedClient({...});
const storage = new Storage({authClient});
```
Additional samples:
- https://github.com/googleapis/google-auth-library-nodejs#sample-usage-1
- https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/downscopedclient.js
Members
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.
This object provides constants to refer to the three permission levels that can be granted to an entity:
gcs.acl.OWNER_ROLE
- ("OWNER")gcs.acl.READER_ROLE
- ("READER")gcs.acl.WRITER_ROLE
- ("WRITER")
Properties:
Name | Type | Description |
---|---|---|
OWNER_ROLE |
string | |
READER_ROLE |
string | |
WRITER_ROLE |
string |
Example
```
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const albums = storage.bucket('albums');
//-
// Make all of the files currently in a bucket publicly readable.
//-
const options = {
entity: 'allUsers',
role: storage.acl.READER_ROLE
};
albums.acl.add(options, function(err, aclObject) {});
//-
// Make any new objects added to a bucket publicly readable.
//-
albums.acl.default.add(options, function(err, aclObject) {});
//-
// Grant a user ownership permissions to a bucket.
//-
albums.acl.add({
entity: 'user-useremail@example.com',
role: storage.acl.OWNER_ROLE
}, function(err, aclObject) {});
//-
// If the callback is omitted, we'll return a Promise.
//-
albums.acl.add(options).then(function(data) {
const aclObject = data[0];
const apiResponse = data[1];
});
```
acl
Reference to Storage.acl.
- See:
-
- Storage.acl
Bucket
Bucket class.
- See:
Channel
Channel class.
- See:
File
File class.
- See:
HmacKey
HmacKey class.
- See:
Methods
bucket(name, optionsopt) → {Bucket}
Get a reference to a Cloud Storage bucket.
Parameters:
Name | Type | Attributes | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
name |
string |
Name of the bucket. |
|||||||||||||
options |
object |
<optional> |
Configuration object. Properties
|
Returns:
Type | Description |
---|---|
Bucket |
- See:
Example
```
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const albums = storage.bucket('albums');
const photos = storage.bucket('photos');
```
channel(id, resourceId) → {Channel}
Reference a channel to receive notifications about changes to your bucket.
Parameters:
Name | Type | Description |
---|---|---|
id |
string |
The ID of the channel. |
resourceId |
string |
The resource ID of the channel. |
Returns:
Type | Description |
---|---|
Channel |
- See:
Example
```
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const channel = storage.channel('id', 'resource-id');
```
createBucket(name, metadataopt, callbackopt) → {Promise.<CreateBucketResponse>}
Create a bucket.
Cloud Storage uses a flat namespace, so you can't create a bucket with a name that is already in use. For more information, see Bucket Naming Guidelines.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
name |
string |
Name of the bucket to create. |
|
metadata |
CreateBucketRequest |
<optional> |
Metadata to set for the bucket. |
callback |
CreateBucketCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<CreateBucketResponse> |
- See:
Throws:
-
If a name is not provided.
- Type
- Error
Examples
```
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const callback = function(err, bucket, apiResponse) {
// `bucket` is a Bucket object.
};
storage.createBucket('new-bucket', callback);
//-
// Create a bucket in a specific location and region. <em>See the <a
// href="https://cloud.google.com/storage/docs/json_api/v1/buckets/insert">
// Official JSON API docs</a> for complete details on the `location`
option.
// </em>
//-
const metadata = {
location: 'US-CENTRAL1',
regional: true
};
storage.createBucket('new-bucket', metadata, callback);
//-
// Create a bucket with a retention policy of 6 months.
//-
const metadata = {
retentionPolicy: {
retentionPeriod: 15780000 // 6 months in seconds.
}
};
storage.createBucket('new-bucket', metadata, callback);
//-
// Enable versioning on a new bucket.
//-
const metadata = {
versioning: {
enabled: true
}
};
storage.createBucket('new-bucket', metadata, callback);
//-
// If the callback is omitted, we'll return a Promise.
//-
storage.createBucket('new-bucket').then(function(data) {
const bucket = data[0];
const apiResponse = data[1];
});
```
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');
// Creates a client
// The bucket in the sample below will be created in the project asscociated with this client.
// For more information, please see https://cloud.google.com/docs/authentication/production or https://googleapis.dev/nodejs/storage/latest/Storage.html
const storage = new Storage();
async function createBucket() {
// Creates a new bucket in the Asia region with the coldline default storage
// class. Leave the second argument blank for default settings.
//
// For default values see: https://cloud.google.com/storage/docs/locations and
// https://cloud.google.com/storage/docs/storage-classes
const [bucket] = await storage.createBucket(bucketName, {
location: 'ASIA',
storageClass: 'COLDLINE',
});
console.log(`Bucket ${bucket.name} created.`);
}
createBucket().catch(console.error);
createHmacKey(serviceAccountEmail, callbackopt) → {Promise.<CreateHmacKeyResponse>}
Create an HMAC key associated with an service account to authenticate requests to the Cloud Storage XML API.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
serviceAccountEmail |
string |
The service account's email address with which the HMAC key is created for. |
|
callback |
CreateHmacKeyCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<CreateHmacKeyResponse> |
Example
```
const {Storage} = require('google-cloud/storage');
const storage = new Storage();
// Replace with your service account's email address
const serviceAccountEmail =
'my-service-account@appspot.gserviceaccount.com';
storage.createHmacKey(serviceAccountEmail, function(err, hmacKey, secret) {
if (!err) {
// Securely store the secret for use with the XML API.
}
});
//-
// If the callback is omitted, we'll return a Promise.
//-
storage.createHmacKey(serviceAccountEmail)
.then((response) => {
const hmacKey = response[0];
const secret = response[1];
// Securely store the secret for use with the XML API.
});
```
getBuckets(queryopt, callbackopt) → {Promise.<GetBucketsResponse>}
Get Bucket objects for all of the buckets in your project.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
query |
GetBucketsRequest |
<optional> |
Query object for listing buckets. |
callback |
GetBucketsCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<GetBucketsResponse> |
Examples
```
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
storage.getBuckets(function(err, buckets) {
if (!err) {
// buckets is an array of Bucket objects.
}
});
//-
// To control how many API requests are made and page through the results
// manually, set `autoPaginate` to `false`.
//-
const callback = function(err, buckets, nextQuery, apiResponse) {
if (nextQuery) {
// More results exist.
storage.getBuckets(nextQuery, callback);
}
// The `metadata` property is populated for you with the metadata at the
// time of fetching.
buckets[0].metadata;
// However, in cases where you are concerned the metadata could have
// changed, use the `getMetadata` method.
buckets[0].getMetadata(function(err, metadata, apiResponse) {});
};
storage.getBuckets({
autoPaginate: false
}, callback);
//-
// If the callback is omitted, we'll return a Promise.
//-
storage.getBuckets().then(function(data) {
const buckets = data[0];
});
```
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');
// Creates a client
const storage = new Storage();
async function listBuckets() {
const [buckets] = await storage.getBuckets();
console.log('Buckets:');
buckets.forEach(bucket => {
console.log(bucket.name);
});
}
listBuckets().catch(console.error);
getBucketsStream(queryopt) → {ReadableStream}
Get Bucket objects for all of the buckets in your project as a readable object stream.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
query |
GetBucketsRequest |
<optional> |
Query object for listing buckets. |
Returns:
Type | Description |
---|---|
ReadableStream |
A readable stream that emits Bucket instances. |
Example
```
storage.getBucketsStream()
.on('error', console.error)
.on('data', function(bucket) {
// bucket is a Bucket object.
})
.on('end', function() {
// All buckets retrieved.
});
//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
storage.getBucketsStream()
.on('data', function(bucket) {
this.end();
});
```
getHmacKeysStream(optionsopt) → {ReadableStream}
Get HmacKey objects for all of the HMAC keys in the project in a readable object stream.
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
options |
GetHmacKeysOptions |
<optional> |
Configuration options. |
Returns:
Type | Description |
---|---|
ReadableStream |
A readable stream that emits HmacKey instances. |
Example
```
storage.getHmacKeysStream()
.on('error', console.error)
.on('data', function(hmacKey) {
// hmacKey is an HmacKey object.
})
.on('end', function() {
// All HmacKey retrieved.
});
//-
// If you anticipate many results, you can end a stream early to prevent
// unnecessary processing and API requests.
//-
storage.getHmacKeysStream()
.on('data', function(bucket) {
this.end();
});
```
getServiceAccount(optionsopt, callbackopt) → {Promise.<GetServiceAccountResponse>}
Get the email address of this project's Google Cloud Storage service account.
See Projects.serviceAccount: get API Documentation See Projects.serviceAccount Resource
Parameters:
Name | Type | Attributes | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
options |
object |
<optional> |
Configuration object. Properties
|
||||||||
callback |
GetServiceAccountCallback |
<optional> |
Callback function. |
Returns:
Type | Description |
---|---|
Promise.<GetServiceAccountResponse> |
Example
```
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
storage.getServiceAccount(function(err, serviceAccount, apiResponse) {
if (!err) {
const serviceAccountEmail = serviceAccount.emailAddress;
}
});
//-
// If the callback is omitted, we'll return a Promise.
//-
storage.getServiceAccount().then(function(data) {
const serviceAccountEmail = data[0].emailAddress;
const apiResponse = data[1];
});
```
hmacKey(accessId, options) → {HmacKey}
Get a reference to an HmacKey object. Note: this does not fetch the HMAC key's metadata. Use HmacKey#get() to retrieve and populate the metadata.
To get a reference to an HMAC key that's not created for a service
account in the same project used to instantiate the Storage client,
supply the project's ID as projectId
in the options
argument.
Parameters:
Name | Type | Description |
---|---|---|
accessId |
string |
The HMAC key's access ID. |
options |
HmacKeyOptions |
HmacKey constructor options. |
Returns:
Type | Description |
---|---|
HmacKey |
- See: