A File object is created from yourBucket object using .
Inheritance
ServiceObject<File> >FilePackage
@google-cloud/storageConstructors
(constructor)(bucket, name, options)
constructor(bucket:Bucket,name:string,options?:FileOptions);
Constructs a file object.
Parameters| Name | Description |
| bucket | Bucket
The Bucket instance this file is attached to. |
| name | string
The name of the remote file. |
| options | FileOptions
Configuration options. |
Exampleconst {Storage} = require('@google-cloud/storage');const storage = newStorage();const myBucket = storage.bucket('my-bucket');const file = myBucket.file('my-file');
Properties
acl
Property Valuebucket
Property Valuegeneration
Property ValueinstancePreconditionOpts
instancePreconditionOpts?:PreconditionOptions;
Property Value| Type | Description |
| PreconditionOptions | |
kmsKeyName
Property Valuemetadata
Property Valuename
Property Valueparent
Property Valuesigner
Property Valuestorage
Property ValueuserProject
Property ValueMethods
copy(destination, options)
copy(destination:string|Bucket|File,options?:CopyOptions):Promise<CopyResponse>;
Parameters| Name | Description |
| destination | string |Bucket |File
|
| options | CopyOptions
|
Returnscopy(destination, callback)
copy(destination:string|Bucket|File,callback:CopyCallback):void;
Parameters| Name | Description |
| destination | string |Bucket |File
|
| callback | CopyCallback
|
Returnscopy(destination, options, callback)
copy(destination:string|Bucket|File,options:CopyOptions,callback:CopyCallback):void;
ParametersReturnscreateReadStream(options)
createReadStream(options?:CreateReadStreamOptions):Readable;
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 theend event when the file is fully downloaded.
ParameterReturns| Type | Description |
| Readable | {ReadableStream} |
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 = newStorage();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(options)
createResumableUpload(options?:CreateResumableUploadOptions):Promise<CreateResumableUploadResponse>;
ParameterReturnscreateResumableUpload(options, callback)
createResumableUpload(options:CreateResumableUploadOptions,callback:CreateResumableUploadCallback):void;
ParametersReturnscreateResumableUpload(callback)
createResumableUpload(callback:CreateResumableUploadCallback):void;
ParameterReturnscreateWriteStream(options)
createWriteStream(options?:CreateWriteStreamOptions):Writable;
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 settingoptions.resumable tofalse.
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 aResumableUploadError.
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 thefinish event when the file is fully uploaded.
SeeUpload Options (Simple or Resumable) SeeObjects: insert API Documentation
ParameterReturns| Type | Description |
| Writable | {WritableStream} |
Exampleconst fs = require('fs');const {Storage} = require('@google-cloud/storage');const storage = newStorage();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. });
deleteResumableCache()
deleteResumableCache():void;
Delete failed resumable upload file cache.
Resumable file upload cache the config file to restart upload in case of failure. In certain scenarios, the resumable upload will not works and upload file cache needs to be deleted to upload the same file.
Following are some of the scenarios.
Resumable file upload failed even though the file is successfully saved on the google storage and need to clean up a resumable file cache to update the same file.
Resumable file upload failed due to pre-condition (i.e generation number is not matched) and want to upload a same file with the new generation number.
ReturnsExampleconst {Storage} = require('@google-cloud/storage');const storage = newStorage();const myBucket = storage.bucket('my-bucket');const file = myBucket.file('my-file', { generation: 0 });const contents = 'This is the contents of the file.';file.save(contents, function(err) { if (err) { file.deleteResumableCache(); }});
disableAutoRetryConditionallyIdempotent_(coreOpts, methodType)
disableAutoRetryConditionallyIdempotent_(coreOpts:any,methodType:AvailableServiceObjectMethods):void;
Parameters| Name | Description |
| coreOpts | any
|
| methodType | AvailableServiceObjectMethods
|
Returnsdownload(options)
download(options?:DownloadOptions):Promise<DownloadResponse>;
ParameterReturnsdownload(options, callback)
download(options:DownloadOptions,callback:DownloadCallback):void;
ParametersReturnsdownload(callback)
download(callback:DownloadCallback):void;
ParameterReturnsgenerateSignedPostPolicyV2(options)
generateSignedPostPolicyV2(options:GenerateSignedPostPolicyV2Options):Promise<GenerateSignedPostPolicyV2Response>;
ParameterReturnsgenerateSignedPostPolicyV2(options, callback)
generateSignedPostPolicyV2(options:GenerateSignedPostPolicyV2Options,callback:GenerateSignedPostPolicyV2Callback):void;
ParametersReturnsgenerateSignedPostPolicyV2(callback)
generateSignedPostPolicyV2(callback:GenerateSignedPostPolicyV2Callback):void;
ParameterReturnsgenerateSignedPostPolicyV4(options)
generateSignedPostPolicyV4(options:GenerateSignedPostPolicyV4Options):Promise<GenerateSignedPostPolicyV4Response>;
ParameterReturnsgenerateSignedPostPolicyV4(options, callback)
generateSignedPostPolicyV4(options:GenerateSignedPostPolicyV4Options,callback:GenerateSignedPostPolicyV4Callback):void;
ParametersReturnsgenerateSignedPostPolicyV4(callback)
generateSignedPostPolicyV4(callback:GenerateSignedPostPolicyV4Callback):void;
ParameterReturnsgetExpirationDate()
getExpirationDate():Promise<GetExpirationDateResponse>;
ReturnsgetExpirationDate(callback)
getExpirationDate(callback:GetExpirationDateCallback):void;
ParameterReturnsgetSignedPolicy(options)
getSignedPolicy(options:GetSignedPolicyOptions):Promise<GetSignedPolicyResponse>;
ParameterReturnsgetSignedPolicy(options, callback)
getSignedPolicy(options:GetSignedPolicyOptions,callback:GetSignedPolicyCallback):void;
ParametersReturnsgetSignedPolicy(callback)
getSignedPolicy(callback:GetSignedPolicyCallback):void;
ParameterReturnsgetSignedUrl(cfg)
getSignedUrl(cfg:GetSignedUrlConfig):Promise<GetSignedUrlResponse>;
ParameterReturnsgetSignedUrl(cfg, callback)
getSignedUrl(cfg:GetSignedUrlConfig,callback:GetSignedUrlCallback):void;
ParametersReturnsisPublic()
isPublic():Promise<IsPublicResponse>;
Returns| Type | Description |
| Promise<IsPublicResponse> | |
isPublic(callback)
isPublic(callback:IsPublicCallback):void;
Parameter| Name | Description |
| callback | IsPublicCallback
|
ReturnsmakePrivate(options)
makePrivate(options?:MakeFilePrivateOptions):Promise<MakeFilePrivateResponse>;
ParameterReturnsmakePrivate(callback)
makePrivate(callback:MakeFilePrivateCallback):void;
ParameterReturnsmakePrivate(options, callback)
makePrivate(options:MakeFilePrivateOptions,callback:MakeFilePrivateCallback):void;
ParametersReturnsmakePublic()
makePublic():Promise<MakeFilePublicResponse>;
ReturnsmakePublic(callback)
makePublic(callback:MakeFilePublicCallback):void;
ParameterReturnsmove(destination, options)
move(destination:string|Bucket|File,options?:MoveOptions):Promise<MoveResponse>;
Parameters| Name | Description |
| destination | string |Bucket |File
|
| options | MoveOptions
|
Returnsmove(destination, callback)
move(destination:string|Bucket|File,callback:MoveCallback):void;
Parameters| Name | Description |
| destination | string |Bucket |File
|
| callback | MoveCallback
|
Returnsmove(destination, options, callback)
move(destination:string|Bucket|File,options:MoveOptions,callback:MoveCallback):void;
ParametersReturnspublicUrl()
The public URL of this File Use to enable anonymous access via the returned URL.
Returns| Type | Description |
| string | {string} |
Exampleconst {Storage} = require('@google-cloud/storage');const storage = newStorage();const bucket = storage.bucket('albums');const file = bucket.file('my-file');// publicUrl will be "https://storage.googleapis.com/albums/my-file"const publicUrl = file.publicUrl();
rename(destinationFile, options)
rename(destinationFile:string|File,options?:RenameOptions):Promise<RenameResponse>;
Parameters| Name | Description |
| destinationFile | string |File
|
| options | RenameOptions
|
Returns| Type | Description |
| Promise<RenameResponse> | |
rename(destinationFile, callback)
rename(destinationFile:string|File,callback:RenameCallback):void;
Parameters| Name | Description |
| destinationFile | string |File
|
| callback | RenameCallback
|
Returnsrename(destinationFile, options, callback)
rename(destinationFile:string|File,options:RenameOptions,callback:RenameCallback):void;
Parameters| Name | Description |
| destinationFile | string |File
|
| options | RenameOptions
|
| callback | RenameCallback
|
Returnsrequest(reqOpts)
request(reqOpts:DecorateRequestOptions):Promise<[ResponseBody,Metadata]>;
Parameter| Name | Description |
| reqOpts | DecorateRequestOptions
|
Returns| Type | Description |
| Promise<[ResponseBody,Metadata]> | |
request(reqOpts, callback)
request(reqOpts:DecorateRequestOptions,callback:BodyResponseCallback):void;
Parameters| Name | Description |
| reqOpts | DecorateRequestOptions
|
| callback | BodyResponseCallback
|
ReturnsrotateEncryptionKey(options)
rotateEncryptionKey(options?:RotateEncryptionKeyOptions):Promise<RotateEncryptionKeyResponse>;
ParameterReturnsrotateEncryptionKey(callback)
rotateEncryptionKey(callback:RotateEncryptionKeyCallback):void;
ParameterReturnsrotateEncryptionKey(options, callback)
rotateEncryptionKey(options:RotateEncryptionKeyOptions,callback:RotateEncryptionKeyCallback):void;
ParametersReturnssave(data, options)
save(data:string|Buffer,options?:SaveOptions):Promise<void>;
Parameters| Name | Description |
| data | string |__global.Buffer
|
| options | SaveOptions
|
Returns| Type | Description |
| Promise<void> | |
save(data, callback)
save(data:string|Buffer,callback:SaveCallback):void;
Parameters| Name | Description |
| data | string |__global.Buffer
|
| callback | SaveCallback
|
Returnssave(data, options, callback)
save(data:string|Buffer,options:SaveOptions,callback:SaveCallback):void;
ParametersReturnssetEncryptionKey(encryptionKey)
setEncryptionKey(encryptionKey:string|Buffer):this;
Parameter| Name | Description |
| encryptionKey | string |__global.Buffer
An AES-256 encryption key. |
Returns| Type | Description |
| this | {File} |
Examplesconst crypto = require('crypto');const {Storage} = require('@google-cloud/storage');const storage = newStorage();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' }); });});
Example of uploading an encrypted file:
/** * TODO(developer): Uncomment the following lines before running the sample. */ // The ID of your GCS bucket // const bucketName = 'your-unique-bucket-name'; // The path to your file to upload // const filePath = 'path/to/your/file'; // The new ID for your GCS file // const destFileName = 'your-new-file-name'; // The key to encrypt the object with // const key = 'TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g='; // Imports the Google Cloud client library const {Storage} = require('@google-cloud/storage'); // Creates a client const storage = newStorage(); async function uploadEncryptedFile() { const options = { destination: destFileName, encryptionKey: Buffer.from(key, 'base64'), }; await storage.bucket(bucketName).upload(filePath, options); console.log( `File ${filePath} uploaded to gs://${bucketName}/${destFileName}` ); } uploadEncryptedFile().catch(console.error);
Example of downloading an encrypted file:
/** * TODO(developer): Uncomment the following lines before running the sample. */ // The ID of your GCS bucket // const bucketName = 'your-unique-bucket-name'; // The ID of your GCS file // const srcFileName = 'your-file-name'; // The path to which the file should be downloaded // const destFileName = '/local/path/to/file.txt'; // The Base64 encoded decryption key, which should be the same key originally // used to encrypt the file // const encryptionKey = 'TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g='; // Imports the Google Cloud client library const {Storage} = require('@google-cloud/storage'); // Creates a client const storage = newStorage(); async function downloadEncryptedFile() { const options = { destination: destFileName, }; // Descrypts and downloads the file. This can only be done with the key used // to encrypt and upload the file. await storage .bucket(bucketName) .file(srcFileName) .setEncryptionKey(Buffer.from(encryptionKey, 'base64')) .download(options); console.log(`File ${srcFileName} downloaded to ${destFileName}`); } downloadEncryptedFile().catch(console.error);
setStorageClass(storageClass, options)
setStorageClass(storageClass:string,options?:SetStorageClassOptions):Promise<SetStorageClassResponse>;
ParametersReturnssetStorageClass(storageClass, options, callback)
setStorageClass(storageClass:string,options:SetStorageClassOptions,callback:SetStorageClassCallback):void;
ParametersReturnssetStorageClass(storageClass, callback)
setStorageClass(storageClass:string,callback?:SetStorageClassCallback):void;
ParametersReturnssetUserProject(userProject)
setUserProject(userProject:string):void;
Set a user project to be billed for all requests made from this File object.
Parameter| Name | Description |
| userProject | string
The user project. |
ReturnsExampleconst {Storage} = require('@google-cloud/storage');const storage = newStorage();const bucket = storage.bucket('albums');const file = bucket.file('my-file');file.setUserProject('grape-spaceship-123');
startResumableUpload_(dup, options)
startResumableUpload_(dup:Duplexify,options:CreateResumableUploadOptions):void;
ParametersReturnsstartSimpleUpload_(dup, options)
startSimpleUpload_(dup:Duplexify,options?:CreateWriteStreamOptions):void;
Takes a readable stream and pipes it to a remote file. UnlikestartResumableUpload_, which uses the resumable upload technique, this method uses a simple upload (all or nothing).
Parameters| Name | Description |
| dup | Duplexify
Duplexify stream of data to pipe to the file. |
| options | CreateWriteStreamOptions
Configuration object. |
Returns