new File(bucket, name[, options])

Constructs a file object.

Example

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

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

Parameters

Name Type Optional Description

bucket

 

 

The Bucket instance this file is attached to.

name

 

 

The name of the remote file.

options

 

Yes

Configuration options.

Methods

copy(destination[, options][, callback]) → Promise containing 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://".

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:

Parameters

Name Type Optional Description

destination

(string, Bucket, or File)

 

Destination file.

options

CopyOptions

Yes

Configuration options. See an

callback

CopyCallback

Yes

Callback function.

See also

Objects: rewrite API Documentation

Throws

Error 

If the destination file is not provided.

Returns

Promise containing CopyResponse 

createReadStream([options]) → 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.

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

Parameter

Name Type Optional Description

options

CreateReadStreamOptions

Yes

Configuration options.

Returns

ReadableStream 

createResumableUpload([options][, callback]) → Promise containing 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.

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

Parameters

Name Type Optional Description

options

CreateResumableUploadOptions

Yes

Configuration options.

callback

CreateResumableUploadCallback

Yes

Callback function.

See also

Resumable upload guide

Returns

Promise containing CreateResumableUploadResponse 

createWriteStream([options]) → 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.

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 {@link 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
// {@link 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.
  });

Parameter

Name Type Optional Description

options

CreateWriteStreamOptions

Yes

Configuration options.

See also

Upload Options (Simple or Resumable)

Objects: insert API Documentation

Returns

WritableStream 

delete([options][, callback]) → Promise containing DeleteFileResponse

Delete the file.

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:

Parameters

Name Type Optional Description

options

object

Yes

Configuration options.

Values in options have the following properties:

Name Type Optional Description

userProject

string

Yes

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

callback

DeleteFileCallback

Yes

Callback function.

See also

Objects: delete API Documentation

Returns

Promise containing DeleteFileResponse 

download([options][, callback]) → Promise containing DownloadResponse

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

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:

Parameters

Name Type Optional Description

options

object

Yes

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

Values in options have the following properties:

Name Type Optional Description

destination

string

Yes

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

userProject

string

Yes

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

callback

DownloadCallback

Yes

Callback function.

Returns

Promise containing DownloadResponse 

exists([options][, callback]) → Promise containing FileExistsResponse

Check if the file exists.

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

Parameters

Name Type Optional Description

options

options

Yes

Configuration options.

Values in options have the following properties:

Name Type Optional Description

userProject

string

Yes

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

callback

FileExistsCallback

Yes

Callback function.

Returns

Promise containing FileExistsResponse 

get([options][, callback]) → Promise containing GetFileResponse

Get a file object and its metadata if it exists.

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

Parameters

Name Type Optional Description

options

options

Yes

Configuration options.

Values in options have the following properties:

Name Type Optional Description

userProject

string

Yes

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

callback

GetFileCallback

Yes

Callback function.

Returns

Promise containing GetFileResponse 

getExpirationDate([callback]) → Promise containing 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.

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

Parameter

Name Type Optional Description

callback

GetExpirationDateCallback

Yes

Callback function.

Returns

Promise containing GetExpirationDateResponse 

getMetadata([options][, callback]) → Promise containing GetFileMetadataResponse

Get the file's metadata.

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:

Parameters

Name Type Optional Description

options

object

Yes

Configuration options.

Values in options have the following properties:

Name Type Optional Description

userProject

string

Yes

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

callback

GetFileMetadataCallback

Yes

Callback function.

See also

Objects: get API Documentation

Returns

Promise containing GetFileMetadataResponse 

getSignedPolicy(options[, callback]) → Promise containing 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.

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

Parameters

Name Type Optional Description

options

object

 

Configuration options.

Values in options have the following properties:

Name Type Optional Description

equals

(array or Array of array)

Yes

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

any type

 

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

startsWith

(array or Array of array)

Yes

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

Yes

ACL for the object from possibly predefined ACLs.

successRedirect

string

Yes

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

successStatus

string

Yes

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

contentLengthRange

object

Yes

contentLengthRange.min

number

Yes

Minimum value for the request's content length.

contentLengthRange.max

number

Yes

Maximum value for the request's content length.

callback

GetSignedPolicyCallback

Yes

Callback function.

See also

Policy Document Reference

Throws

Error 

If an expiration timestamp from the past is given.

Error 

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

Error 

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

Returns

Promise containing GetSignedPolicyResponse 

getSignedUrl(config[, callback]) → Promise containing 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.

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:

Parameters

Name Type Optional Description

config

object

 

Configuration object.

Values in config have the following properties:

Name Type Optional 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

Yes

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

Defaults to 'v2'.

cname

string

Yes

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

contentMd5

string

Yes

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

Yes

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

any type

 

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

extensionHeaders

object

Yes

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

Yes

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

Yes

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

responseType

string

Yes

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

callback

GetSignedUrlCallback

Yes

Callback function.

See also

Signed URLs Reference

Throws

Error 

if an expiration timestamp from the past is given.

Returns

Promise containing GetSignedUrlResponse 

isPublic([callback]) → Promise containing 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.

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

Parameter

Name Type Optional Description

callback

IsPublicCallback

Yes

Callback function.

Returns

Promise containing IsPublicResponse 

makePrivate([options][, callback]) → Promise containing 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.

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

Parameters

Name Type Optional Description

options

MakeFilePrivateOptions

Yes

Configuration options.

callback

MakeFilePrivateCallback

Yes

Callback function.

See also

Objects: patch API Documentation

Returns

Promise containing MakeFilePrivateResponse 

makePublic([callback]) → Promise containing MakeFilePublicResponse

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

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:

Parameter

Name Type Optional Description

callback

MakeFilePublicCallback

Yes

Callback function.

See also

ObjectAccessControls: insert API Documentation

Returns

Promise containing MakeFilePublicResponse 

move(destination[, callback]) → Promise containing 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.

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:

Parameters

Name Type Optional Description

destination

(string, Bucket, or File)

 

Destination file.

callback

MoveCallback

Yes

Callback function.

See also

Objects: copy API Documentation

Throws

Error 

If the destination file is not provided.

Returns

Promise containing MoveResponse 

rotateEncryptionKey([options][, callback]) → Promise containing File

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

Example

include:samples/encryption.js

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

Parameters

Name Type Optional Description

options

RotateEncryptionKeyOptions

Yes

Configuration options.

callback

RotateEncryptionKeyCallback

Yes

See also

Customer-supplied Encryption Keys

Returns

Promise containing File 

save(data[, options][, callback]) → 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.

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

Parameters

Name Type Optional Description

data

any type

 

The data to write to a file.

options

SaveOptions

Yes

See File#createWriteStream's options parameter.

callback

SaveCallback

Yes

Callback function.

Returns

Promise 

setEncryptionKey(encryptionKey) → File

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

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:

Parameter

Name Type Optional Description

encryptionKey

(string or buffer)

 

An AES-256 encryption key.

See also

Customer-supplied Encryption Keys

Returns

File 

setMetadata([metadata][, options][, callback]) → Promise containing 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.

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

Parameters

Name Type Optional Description

metadata

object

Yes

The metadata you wish to update.

options

SetFileMetadataOptions

Yes

Configuration options.

callback

SetFileMetadataCallback

Yes

Callback function.

See also

Objects: patch API Documentation

Returns

Promise containing SetFileMetadataResponse 

setStorageClass(storageClass[, options][, callback]) → Promise containing SetStorageClassResponse

Set the storage class for this file.

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

Parameters

Name Type Optional Description

storageClass

string

 

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

options

SetStorageClassOptions

Yes

Configuration options.

Values in options have the following properties:

Name Type Optional Description

userProject

string

Yes

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

callback

SetStorageClassCallback

Yes

Callback function.

See also

Per-Object Storage Class

Storage Classes

Returns

Promise containing SetStorageClassResponse 

setUserProject(userProject)

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

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

Parameter

Name Type Optional Description

userProject

string

 

The user project.