File

File

A File object is created from your Bucket object using Bucket#file.

Constructor

new File(bucket, name, optionsopt)

Constructs a file object.

Parameters:
Name Type Attributes Description
bucket Bucket

The Bucket instance this file is attached to.

name string

The name of the remote file.

options FileOptions <optional>

Configuration options.

Source:
Example
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

Methods

copy(destination, optionsopt, callbackopt) → {Promise.<CopyResponse>}

Copy this file to another file. By default, this will copy the file to the same bucket, but you can choose to copy it to another Bucket by providing a Bucket or File object or a URL starting with "gs://".

Parameters:
Name Type Attributes Description
destination string | Bucket | File

Destination file.

options CopyOptions <optional>

Configuration options. See an

callback CopyCallback <optional>

Callback function.

Source:
See:
Throws:

If the destination file is not provided.

Type
Error
Examples
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();

//-
// You can pass in a variety of types for the destination.
//
// For all of the below examples, assume we are working with the following
// Bucket and File objects.
//-
const bucket = storage.bucket('my-bucket');
const file = bucket.file('my-image.png');

//-
// If you pass in a string for the destination, the file is copied to its
// current bucket, under the new name provided.
//-
file.copy('my-image-copy.png', function(err, copiedFile, apiResponse) {
  // `my-bucket` now contains:
  // - "my-image.png"
  // - "my-image-copy.png"

  // `copiedFile` is an instance of a File object that refers to your new
  // file.
});

//-
// If you pass in a string starting with "gs://" for the destination, the
// file is copied to the other bucket and under the new name provided.
//-
const newLocation = 'gs://another-bucket/my-image-copy.png';
file.copy(newLocation, function(err, copiedFile, apiResponse) {
  // `my-bucket` still contains:
  // - "my-image.png"
  //
  // `another-bucket` now contains:
  // - "my-image-copy.png"

  // `copiedFile` is an instance of a File object that refers to your new
  // file.
});

//-
// If you pass in a Bucket object, the file will be copied to that bucket
// using the same name.
//-
const anotherBucket = storage.bucket('another-bucket');
file.copy(anotherBucket, function(err, copiedFile, apiResponse) {
  // `my-bucket` still contains:
  // - "my-image.png"
  //
  // `another-bucket` now contains:
  // - "my-image.png"

  // `copiedFile` is an instance of a File object that refers to your new
  // file.
});

//-
// If you pass in a File object, you have complete control over the new
// bucket and filename.
//-
const anotherFile = anotherBucket.file('my-awesome-image.png');
file.copy(anotherFile, function(err, copiedFile, apiResponse) {
  // `my-bucket` still contains:
  // - "my-image.png"
  //
  // `another-bucket` now contains:
  // - "my-awesome-image.png"

  // Note:
  // The `copiedFile` parameter is equal to `anotherFile`.
});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.copy(newLocation).then(function(data) {
  const newFile = data[0];
  const apiResponse = data[1];
});

include:samples/files.js

region_tag:storage_copy_file
Another example:

createReadStream(optionsopt) → {ReadableStream}

Create a readable stream to read the contents of the remote file. It can be piped to a writable stream or listened to for 'data' events to read a file's contents.

In the unlikely event there is a mismatch between what you downloaded and the version in your Bucket, your error handler will receive an error with code "CONTENT_DOWNLOAD_MISMATCH". If you receive this error, the best recourse is to try downloading the file again.

For faster crc32c computation, you must manually install fast-crc32c:

$ npm install --save fast-crc32c

NOTE: Readable streams will emit the end event when the file is fully downloaded.

Parameters:
Name Type Attributes Description
options CreateReadStreamOptions <optional>

Configuration options.

Source:
Example
//-
// <h4>Downloading a File</h4>
//
// The example below demonstrates how we can reference a remote file, then
// pipe its contents to a local file. This is effectively creating a local
// backup of your remote data.
//-
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('my-bucket');

const fs = require('fs');
const remoteFile = bucket.file('image.png');
const localFilename = '/Users/stephen/Photos/image.png';

remoteFile.createReadStream()
  .on('error', function(err) {})
  .on('response', function(response) {
    // Server connected and responded with the specified status and headers.
   })
  .on('end', function() {
    // The file is fully downloaded.
  })
  .pipe(fs.createWriteStream(localFilename));

//-
// To limit the downloaded data to only a byte range, pass an options
object.
//-
const logFile = myBucket.file('access_log');
logFile.createReadStream({
    start: 10000,
    end: 20000
  })
  .on('error', function(err) {})
  .pipe(fs.createWriteStream('/Users/stephen/logfile.txt'));

//-
// To read a tail byte range, specify only `options.end` as a negative
// number.
//-
const logFile = myBucket.file('access_log');
logFile.createReadStream({
    end: -100
  })
  .on('error', function(err) {})
  .pipe(fs.createWriteStream('/Users/stephen/logfile.txt'));

createResumableUpload(optionsopt, callbackopt) → {Promise.<CreateResumableUploadResponse>}

Create a unique resumable upload session URI. This is the first step when performing a resumable upload.

See the Resumable upload guide for more on how the entire process works.

Note

If you are just looking to perform a resumable upload without worrying about any of the details, see File#createWriteStream. Resumable uploads are performed by default.

Parameters:
Name Type Attributes Description
options CreateResumableUploadOptions <optional>

Configuration options.

callback CreateResumableUploadCallback <optional>

Callback function.

Source:
See:
Example
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');
file.createResumableUpload(function(err, uri) {
  if (!err) {
    // `uri` can be used to PUT data to.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.createResumableUpload().then(function(data) {
  const uri = data[0];
});

createWriteStream(optionsopt) → {WritableStream}

Create a writable stream to overwrite the contents of the file in your bucket.

A File object can also be used to create files for the first time.

Resumable uploads are automatically enabled and must be shut off explicitly by setting options.resumable to false.

Resumable uploads require write access to the $HOME directory. Through config-store, some metadata is stored. By default, if the directory is not writable, we will fall back to a simple upload. However, if you explicitly request a resumable upload, and we cannot write to the config directory, we will return a ResumableUploadError.

There is some overhead when using a resumable upload that can cause noticeable performance degradation while uploading a series of small files. When uploading files less than 10MB, it is recommended that the resumable feature is disabled.

For faster crc32c computation, you must manually install fast-crc32c:

$ npm install --save fast-crc32c

NOTE: Writable streams will emit the finish event when the file is fully uploaded.

Parameters:
Name Type Attributes Description
options CreateWriteStreamOptions <optional>

Configuration options.

Source:
See:
Example
const fs = require('fs');
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

//-
// <h4>Uploading a File</h4>
//
// Now, consider a case where we want to upload a file to your bucket. You
// have the option of using Bucket#upload, but that is just
// a convenience method which will do the following.
//-
fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
  .pipe(file.createWriteStream())
  .on('error', function(err) {})
  .on('finish', function() {
    // The file upload is complete.
  });

//-
// <h4>Uploading a File with gzip compression</h4>
//-
fs.createReadStream('/Users/stephen/site/index.html')
  .pipe(file.createWriteStream({ gzip: true }))
  .on('error', function(err) {})
  .on('finish', function() {
    // The file upload is complete.
  });

//-
// Downloading the file with `createReadStream` will automatically decode
// the file.
//-

//-
// <h4>Uploading a File with Metadata</h4>
//
// One last case you may run into is when you want to upload a file to your
// bucket and set its metadata at the same time. Like above, you can use
// Bucket#upload to do this, which is just a wrapper around
// the following.
//-
fs.createReadStream('/Users/stephen/Photos/birthday-at-the-zoo/panda.jpg')
  .pipe(file.createWriteStream({
    metadata: {
      contentType: 'image/jpeg',
      metadata: {
        custom: 'metadata'
      }
    }
  }))
  .on('error', function(err) {})
  .on('finish', function() {
    // The file upload is complete.
  });

delete(optionsopt, callbackopt) → {Promise.<DeleteFileResponse>}

Delete the file.

Parameters:
Name Type Attributes Description
options object <optional>

Configuration options.

Properties
Name Type Attributes Description
userProject string <optional>

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

callback DeleteFileCallback <optional>

Callback function.

Source:
See:
Examples
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');
file.delete(function(err, apiResponse) {});

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

include:samples/files.js

region_tag:storage_delete_file
Another example:

download(optionsopt, callbackopt) → {Promise.<DownloadResponse>}

Convenience method to download a file into memory or to a local destination.

Parameters:
Name Type Attributes Description
options object <optional>

Configuration options. The arguments match those passed to File#createReadStream.

Properties
Name Type Attributes Description
destination string <optional>

Local file path to write the file's contents to.

userProject string <optional>

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

callback DownloadCallback <optional>

Callback function.

Source:
Examples
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

//-
// Download a file into memory. The contents will be available as the
second
// argument in the demonstration below, `contents`.
//-
file.download(function(err, contents) {});

//-
// Download a file to a local destination.
//-
file.download({
  destination: '/Users/me/Desktop/file-backup.txt'
}, function(err) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.download().then(function(data) {
  const contents = data[0];
});

include:samples/files.js

region_tag:storage_download_file
Another example:

include:samples/encryption.js

region_tag:storage_download_encrypted_file
Example of downloading an encrypted file:

include:samples/requesterPays.js

region_tag:storage_download_file_requester_pays
Example of downloading a file where the requester pays:

exists(optionsopt, callbackopt) → {Promise.<FileExistsResponse>}

Check if the file exists.

Parameters:
Name Type Attributes Description
options options <optional>

Configuration options.

Properties
Name Type Attributes Description
userProject string <optional>

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

callback FileExistsCallback <optional>

Callback function.

Source:
Example
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

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

//-
// If the callback is omitted, we'll return a Promise.
//-
file.exists().then(function(data) {
  const exists = data[0];
});

get(optionsopt, callbackopt) → {Promise.<GetFileResponse>}

Get a file object and its metadata if it exists.

Parameters:
Name Type Attributes Description
options options <optional>

Configuration options.

Properties
Name Type Attributes Description
userProject string <optional>

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

callback GetFileCallback <optional>

Callback function.

Source:
Example
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

file.get(function(err, file, apiResponse) {
  // file.metadata` has been populated.
});

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

getExpirationDate(callbackopt) → {Promise.<GetExpirationDateResponse>}

If this bucket has a retention policy defined, use this method to get a Date object representing the earliest time this file will expire.

Parameters:
Name Type Attributes Description
callback GetExpirationDateCallback <optional>

Callback function.

Source:
Example
const storage = require('@google-cloud/storage')();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

file.getExpirationDate(function(err, expirationDate) {
  // expirationDate is a Date object.
});

getMetadata(optionsopt, callbackopt) → {Promise.<GetFileMetadataResponse>}

Get the file's metadata.

Parameters:
Name Type Attributes Description
options object <optional>

Configuration options.

Properties
Name Type Attributes Description
userProject string <optional>

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

callback GetFileMetadataCallback <optional>

Callback function.

Source:
See:
Examples
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

file.getMetadata(function(err, metadata, apiResponse) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.getMetadata().then(function(data) {
  const metadata = data[0];
  const apiResponse = data[1];
});

include:samples/files.js

region_tag:storage_get_metadata
Another example:

getSignedPolicy(options, callbackopt) → {Promise.<GetSignedPolicyResponse>}

Get a signed policy document to allow a user to upload data with a POST request.

In Google Cloud Platform environments, such as Cloud Functions and App Engine, you usually don't provide a keyFilename or credentials during instantiation. In those environments, we call the signBlob API to create a signed policy. That API requires either the https://www.googleapis.com/auth/iam or https://www.googleapis.com/auth/cloud-platform scope, so be sure they are enabled.

Parameters:
Name Type Attributes Description
options object

Configuration options.

Properties
Name Type Attributes Description
equals array | Array.<array> <optional>

Array of request parameters and their expected value (e.g. [['$', '']]). Values are translated into equality constraints in the conditions field of the policy document (e.g. ['eq', '$', '']). If only one equality condition is to be specified, options.equals can be a one- dimensional array (e.g. ['$', '']).

expires *

A timestamp when this policy will expire. Any value given is passed to new Date().

startsWith array | Array.<array> <optional>

Array of request parameters and their expected prefixes (e.g. [['$', '']). Values are translated into starts-with constraints in the conditions field of the policy document (e.g. ['starts-with', '$', '']). If only one prefix condition is to be specified, options.startsWith can be a one- dimensional array (e.g. ['$', '']).

acl string <optional>

ACL for the object from possibly predefined ACLs.

successRedirect string <optional>

The URL to which the user client is redirected if the upload is successful.

successStatus string <optional>

The status of the Google Storage response if the upload is successful (must be string).

contentLengthRange object <optional>
Properties
Name Type Attributes Description
min number <optional>

Minimum value for the request's content length.

max number <optional>

Maximum value for the request's content length.

callback GetSignedPolicyCallback <optional>

Callback function.

Source:
See:
Throws:
  • If an expiration timestamp from the past is given.

    Type
    Error
  • If options.equals has an array with less or more than two members.

    Type
    Error
  • If options.startsWith has an array with less or more than two members.

    Type
    Error
Example
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');
const options = {
  equals: ['$Content-Type', 'image/jpeg'],
  expires: '10-25-2022',
  contentLengthRange: {
    min: 0,
    max: 1024
  }
};

file.getSignedPolicy(options, function(err, policy) {
  // policy.string: the policy document in plain text.
  // policy.base64: the policy document in base64.
  // policy.signature: the policy signature in base64.
});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.getSignedPolicy(options).then(function(data) {
  const policy = data[0];
});

getSignedUrl(config, callbackopt) → {Promise.<GetSignedUrlResponse>}

Get a signed URL to allow limited time access to the file.

In Google Cloud Platform environments, such as Cloud Functions and App Engine, you usually don't provide a keyFilename or credentials during instantiation. In those environments, we call the signBlob API to create a signed URL. That API requires either the https://www.googleapis.com/auth/iam or https://www.googleapis.com/auth/cloud-platform scope, so be sure they are enabled.

Parameters:
Name Type Attributes Description
config object

Configuration object.

Properties
Name Type Attributes Default Description
action string

"read" (HTTP: GET), "write" (HTTP: PUT), or "delete" (HTTP: DELETE), "resumable" (HTTP: POST). When using "resumable", the header X-Goog-Resumable: start has to be sent when making a request with the signed URL.

version string <optional>
'v2'

The signing version to use, either 'v2' or 'v4.

cname string <optional>

The cname for this bucket, i.e., "https://cdn.example.com".

contentMd5 string <optional>

The MD5 digest value in base64. Just like if you provide this, the client must provide this HTTP header with this same value in its request, so to if this parameter is not provided here, the client must not provide any value for this HTTP header in its request.

contentType string <optional>

Just like if you provide this, the client must provide this HTTP header with this same value in its request, so to if this parameter is not provided here, the client must not provide any value for this HTTP header in its request.

expires *

A timestamp when this link will expire. Any value given is passed to new Date(). Note: 'v4' supports maximum duration of 7 days (604800 seconds) from now. See reference

extensionHeaders object <optional>

If these headers are used, the server will check to make sure that the client provides matching values. See Canonical extension headers for the requirements of this feature, most notably: - The header name must be prefixed with x-goog- - The header name must be all lowercase Note: Multi-valued header passed as an array in the extensionHeaders object is converted into a string, delimited by , with no space. Requests made using the signed URL will need to delimit multi-valued headers using a single , as well, or else the server will report a mismatched signature.

promptSaveAs string <optional>

The filename to prompt the user to save the file as when the signed url is accessed. This is ignored if config.responseDisposition is set.

responseDisposition string <optional>

The response-content-disposition parameter of the signed url.

responseType string <optional>

The response-content-type parameter of the signed url.

callback GetSignedUrlCallback <optional>

Callback function.

Source:
See:
Throws:

if an expiration timestamp from the past is given.

Type
Error
Examples
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

//-
// Generate a URL that allows temporary access to download your file.
//-
const request = require('request');

const config = {
  action: 'read',
  expires: '03-17-2025'
};

file.getSignedUrl(config, function(err, url) {
  if (err) {
    console.error(err);
    return;
  }

  // The file is now available to read from this URL.
  request(url, function(err, resp) {
    // resp.statusCode = 200
  });
});

//-
// Generate a URL to allow write permissions. This means anyone with this
URL
// can send a POST request with new data that will overwrite the file.
//-
file.getSignedUrl({
  action: 'write',
  expires: '03-17-2025'
}, function(err, url) {
  if (err) {
    console.error(err);
    return;
  }

  // The file is now available to be written to.
  const writeStream = request.put(url);
  writeStream.end('New data');

  writeStream.on('complete', function(resp) {
    // Confirm the new content was saved.
    file.download(function(err, fileContents) {
      console.log('Contents:', fileContents.toString());
      // Contents: New data
    });
  });
});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.getSignedUrl(config).then(function(data) {
  const url = data[0];
});

include:samples/files.js

region_tag:storage_generate_signed_url
Another example:

isPublic(callbackopt) → {Promise.<IsPublicResponse>}

Check whether this file is public or not by sending a HEAD request without credentials. No errors from the server indicates that the current file is public. A 403-Forbidden error https://cloud.google.com/storage/docs/json_api/v1/status-codes#403_Forbidden indicates that file is private. Any other non 403 error is propagated to user.

Parameters:
Name Type Attributes Description
callback IsPublicCallback <optional>

Callback function.

Source:
Example
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

//-
// Check whether the file is publicly accessible.
//-
file.isPublic(function(err, resp) {
  if (err) {
    console.error(err);
    return;
  }
  console.log(`the file ${file.id} is public: ${resp}`) ;
})
//-
// If the callback is omitted, we'll return a Promise.
//-
file.isPublic().then(function(data) {
  const resp = data[0];
});

makePrivate(optionsopt, callbackopt) → {Promise.<MakeFilePrivateResponse>}

Make a file private to the project and remove all other permissions. Set options.strict to true to make the file private to only the owner.

Parameters:
Name Type Attributes Description
options MakeFilePrivateOptions <optional>

Configuration options.

callback MakeFilePrivateCallback <optional>

Callback function.

Source:
See:
Example
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

//-
// Set the file private so only project maintainers can see and modify it.
//-
file.makePrivate(function(err) {});

//-
// Set the file private so only the owner can see and modify it.
//-
file.makePrivate({ strict: true }, function(err) {});

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

makePublic(callbackopt) → {Promise.<MakeFilePublicResponse>}

Set a file to be publicly readable and maintain all previous permissions.

Parameters:
Name Type Attributes Description
callback MakeFilePublicCallback <optional>

Callback function.

Source:
See:
Examples
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

file.makePublic(function(err, apiResponse) {});

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

include:samples/files.js

region_tag:storage_make_public
Another example:

move(destination, callbackopt) → {Promise.<MoveResponse>}

Move this file to another location. By default, this will rename the file and keep it in the same bucket, but you can choose to move it to another Bucket by providing a Bucket or File object or a URL beginning with "gs://".

Warning: There is currently no atomic move method in the Cloud Storage API, so this method is a composition of File#copy (to the new location) and File#delete (from the old location). While unlikely, it is possible that an error returned to your callback could be triggered from either one of these API calls failing, which could leave a duplicate file lingering.

Parameters:
Name Type Attributes Description
destination string | Bucket | File

Destination file.

callback MoveCallback <optional>

Callback function.

Source:
See:
Throws:

If the destination file is not provided.

Type
Error
Examples
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
//-
// You can pass in a variety of types for the destination.
//
// For all of the below examples, assume we are working with the following
// Bucket and File objects.
//-
const bucket = storage.bucket('my-bucket');
const file = bucket.file('my-image.png');

//-
// If you pass in a string for the destination, the file is moved to its
// current bucket, under the new name provided.
//-
file.move('my-image-new.png', function(err, destinationFile, apiResponse) {
  // `my-bucket` no longer contains:
  // - "my-image.png"
  // but contains instead:
  // - "my-image-new.png"

  // `destinationFile` is an instance of a File object that refers to your
  // new file.
});

//-
// If you pass in a string starting with "gs://" for the destination, the
// file is copied to the other bucket and under the new name provided.
//-
const newLocation = 'gs://another-bucket/my-image-new.png';
file.move(newLocation, function(err, destinationFile, apiResponse) {
  // `my-bucket` no longer contains:
  // - "my-image.png"
  //
  // `another-bucket` now contains:
  // - "my-image-new.png"

  // `destinationFile` is an instance of a File object that refers to your
  // new file.
});

//-
// If you pass in a Bucket object, the file will be moved to that bucket
// using the same name.
//-
const anotherBucket = gcs.bucket('another-bucket');

file.move(anotherBucket, function(err, destinationFile, apiResponse) {
  // `my-bucket` no longer contains:
  // - "my-image.png"
  //
  // `another-bucket` now contains:
  // - "my-image.png"

  // `destinationFile` is an instance of a File object that refers to your
  // new file.
});

//-
// If you pass in a File object, you have complete control over the new
// bucket and filename.
//-
const anotherFile = anotherBucket.file('my-awesome-image.png');

file.move(anotherFile, function(err, destinationFile, apiResponse) {
  // `my-bucket` no longer contains:
  // - "my-image.png"
  //
  // `another-bucket` now contains:
  // - "my-awesome-image.png"

  // Note:
  // The `destinationFile` parameter is equal to `anotherFile`.
});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.move('my-image-new.png').then(function(data) {
  const destinationFile = data[0];
  const apiResponse = data[1];
});

include:samples/files.js

region_tag:storage_move_file
Another example:

rotateEncryptionKey(optionsopt, callbackopt) → {Promise.<File>}

This method allows you to update the encryption key associated with this file.

Parameters:
Name Type Attributes Description
options RotateEncryptionKeyOptions <optional>

Configuration options.

callback RotateEncryptionKeyCallback <optional>
Source:
See:
Example

include:samples/encryption.js

region_tag:storage_rotate_encryption_key
Example of rotating the encryption key for this file:

save(data, optionsopt, callbackopt) → {Promise}

Write arbitrary data to a file.

This is a convenience method which wraps File#createWriteStream.

Resumable uploads are automatically enabled and must be shut off explicitly by setting options.resumable to false.

There is some overhead when using a resumable upload that can cause noticeable performance degradation while uploading a series of small files. When uploading files less than 10MB, it is recommended that the resumable feature is disabled.

Parameters:
Name Type Attributes Description
data *

The data to write to a file.

options SaveOptions <optional>

See File#createWriteStream's options parameter.

callback SaveCallback <optional>

Callback function.

Source:
Example
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');
const contents = 'This is the contents of the file.';

file.save(contents, function(err) {
  if (!err) {
    // File written successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.save(contents).then(function() {});

setEncryptionKey(encryptionKey) → {File}

The Storage API allows you to use a custom key for server-side encryption.

Parameters:
Name Type Description
encryptionKey string | buffer

An AES-256 encryption key.

Source:
See:
Examples
const crypto = require('crypto');
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const encryptionKey = crypto.randomBytes(32);

const fileWithCustomEncryption = myBucket.file('my-file');
fileWithCustomEncryption.setEncryptionKey(encryptionKey);

const fileWithoutCustomEncryption = myBucket.file('my-file');

fileWithCustomEncryption.save('data', function(err) {
  // Try to download with the File object that hasn't had
  // `setEncryptionKey()` called:
  fileWithoutCustomEncryption.download(function(err) {
    // We will receive an error:
    //   err.message === 'Bad Request'

    // Try again with the File object we called `setEncryptionKey()` on:
    fileWithCustomEncryption.download(function(err, contents) {
      // contents.toString() === 'data'
    });
  });
});

include:samples/encryption.js

region_tag:storage_upload_encrypted_file
Example of uploading an encrypted file:

include:samples/encryption.js

region_tag:storage_download_encrypted_file
Example of downloading an encrypted file:

setMetadata(metadataopt, optionsopt, callbackopt) → {Promise.<SetFileMetadataResponse>}

Merge the given metadata with the current remote file's metadata. This will set metadata if it was previously unset or update previously set metadata. To unset previously set metadata, set its value to null.

You can set custom key/value pairs in the metadata key of the given object, however the other properties outside of this object must adhere to the official API documentation.

NOTE: multiple calls to setMetadata in parallel might result in unpredictable results. See issue.

See the examples below for more information.

Parameters:
Name Type Attributes Description
metadata object <optional>

The metadata you wish to update.

options SetFileMetadataOptions <optional>

Configuration options.

callback SetFileMetadataCallback <optional>

Callback function.

Source:
See:
Example
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');

const metadata = {
  contentType: 'application/x-font-ttf',
  metadata: {
    my: 'custom',
    properties: 'go here'
  }
};

file.setMetadata(metadata, function(err, apiResponse) {});

// Assuming current metadata = { hello: 'world', unsetMe: 'will do' }
file.setMetadata({
  metadata: {
    abc: '123', // will be set.
    unsetMe: null, // will be unset (deleted).
    hello: 'goodbye' // will be updated from 'world' to 'goodbye'.
  }
}, function(err, apiResponse) {
  // metadata should now be { abc: '123', hello: 'goodbye' }
});

//-
// Set a temporary hold on this file from its bucket's retention period
// configuration.
//
file.setMetadata({
  temporaryHold: true
}, function(err, apiResponse) {});

//-
// Alternatively, you may set a temporary hold. This will follow the
// same behavior as an event-based hold, with the exception that the
// bucket's retention policy will not renew for this file from the time
// the hold is released.
//-
file.setMetadata({
  eventBasedHold: true
}, function(err, apiResponse) {});

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

setStorageClass(storageClass, optionsopt, callbackopt) → {Promise.<SetStorageClassResponse>}

Set the storage class for this file.

Parameters:
Name Type Attributes Description
storageClass string

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

options SetStorageClassOptions <optional>

Configuration options.

Properties
Name Type Attributes Description
userProject string <optional>

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

callback SetStorageClassCallback <optional>

Callback function.

Source:
See:
Example
file.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.
//-
file.setStorageClass('regional').then(function() {});

setUserProject(userProject)

Set a user project to be billed for all requests made from this File object.

Parameters:
Name Type Description
userProject string

The user project.

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

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