@google-cloud/storage
- Version 7.13.0
- Published
- 1.67 MB
- 15 dependencies
- Apache-2.0 license
Install
npm i @google-cloud/storage
yarn add @google-cloud/storage
pnpm add @google-cloud/storage
Overview
Cloud Storage Client Library for Node.js
Index
Variables
Functions
Classes
Bucket
- acl
- addLifecycleRule()
- cloudStorageURI
- combine()
- crc32cGenerator
- createChannel()
- createNotification()
- deleteFiles()
- deleteLabels()
- disableAutoRetryConditionallyIdempotent_()
- disableRequesterPays()
- enableLogging()
- enableRequesterPays()
- file()
- getFiles()
- getFilesStream()
- getId()
- getLabels()
- getNotifications()
- getSignedUrl()
- iam
- instancePreconditionOpts
- lock()
- makeAllFilesPublicPrivate_()
- makePrivate()
- makePublic()
- name
- notification()
- removeRetentionPeriod()
- request()
- setCorsConfiguration()
- setLabels()
- setMetadata()
- setRetentionPeriod()
- setStorageClass()
- setUserProject()
- signer
- storage
- upload()
- userProject
File
- acl
- bucket
- cloudStorageURI
- copy()
- crc32cGenerator
- createReadStream()
- createResumableUpload()
- createWriteStream()
- delete()
- disableAutoRetryConditionallyIdempotent_()
- download()
- from()
- generateSignedPostPolicyV2()
- generateSignedPostPolicyV4()
- generation
- get()
- getExpirationDate()
- getSignedUrl()
- instancePreconditionOpts
- isPublic()
- kmsKeyName
- makePrivate()
- makePublic()
- move()
- name
- parent
- publicUrl()
- rename()
- request()
- restore()
- rotateEncryptionKey()
- save()
- setEncryptionKey()
- setMetadata()
- setStorageClass()
- setUserProject()
- signer
- startResumableUpload_()
- startSimpleUpload_()
- storage
- userProject
Interfaces
BucketMetadata
- acl
- autoclass
- billing
- cors
- customPlacementConfig
- defaultEventBasedHold
- defaultObjectAcl
- encryption
- hierarchicalNamespace
- iamConfiguration
- labels
- lifecycle
- location
- locationType
- logging
- metageneration
- name
- objectRetention
- owner
- projectNumber
- retentionPolicy
- rpo
- softDeletePolicy
- storageClass
- timeCreated
- updated
- versioning
- website
FileMetadata
- acl
- bucket
- cacheControl
- componentCount
- contentDisposition
- contentEncoding
- contentLanguage
- contentType
- crc32c
- customerEncryption
- customTime
- eventBasedHold
- eventBasedHoldReleaseTime
- generation
- hardDeleteTime
- kmsKeyName
- md5Hash
- mediaLink
- metadata
- metageneration
- name
- owner
- retention
- retentionExpirationTime
- size
- softDeleteTime
- storageClass
- temporaryHold
- timeCreated
- timeDeleted
- timeStorageClassUpdated
- updated
Enums
Type Aliases
- AddAclResponse
- BucketExistsCallback
- BucketExistsResponse
- BucketLockResponse
- CombineResponse
- CopyResponse
- CreateBucketResponse
- CreateChannelResponse
- CreateHmacKeyResponse
- CreateNotificationResponse
- CreateResumableUploadResponse
- DeleteBucketResponse
- DeleteFileResponse
- DeleteLabelsCallback
- DeleteLabelsResponse
- DisableRequesterPaysResponse
- DownloadCallback
- DownloadResponse
- EnableRequesterPaysResponse
- FileExistsResponse
- GenerateSignedPostPolicyV2Response
- GenerateSignedPostPolicyV4Response
- GetAclResponse
- GetBucketMetadataResponse
- GetBucketResponse
- GetBucketsResponse
- GetExpirationDateResponse
- GetFileMetadataResponse
- GetFileResponse
- GetFilesResponse
- GetHmacKeysResponse
- GetLabelsResponse
- GetNotificationMetadataResponse
- GetNotificationResponse
- GetNotificationsResponse
- GetPolicyResponse
- GetServiceAccountResponse
- GetSignedUrlResponse
- HmacKeyMetadataResponse
- MakeBucketPrivateResponse
- MakeBucketPublicResponse
- MakeFilePrivateCallback
- MakeFilePrivateResponse
- MakeFilePublicResponse
- MoveResponse
- MultiPartHelperGenerator
- PredefinedAcl
- RemoveAclResponse
- RotateEncryptionKeyCallback
- RotateEncryptionKeyOptions
- RotateEncryptionKeyResponse
- SetBucketMetadataResponse
- SetFileMetadataResponse
- SetLabelsResponse
- SetPolicyResponse
- SetStorageClassResponse
- TestIamPermissionsResponse
- UpdateAclResponse
- UploadResponse
Variables
variable CRC32C_DEFAULT_VALIDATOR_GENERATOR
const CRC32C_DEFAULT_VALIDATOR_GENERATOR: CRC32CValidatorGenerator;
variable CRC32C_EXCEPTION_MESSAGES
const CRC32C_EXCEPTION_MESSAGES: { readonly INVALID_INIT_BASE64_RANGE: (l: number) => string; readonly INVALID_INIT_BUFFER_LENGTH: (l: number) => string; readonly INVALID_INIT_INTEGER: (l: number) => string;};
variable CRC32C_EXTENSION_TABLE
const CRC32C_EXTENSION_TABLE: Int32Array;
variable CRC32C_EXTENSIONS
const CRC32C_EXTENSIONS: readonly [ 0, 4067132163, 3778769143, 324072436, 3348797215, 904991772, 648144872, 3570033899, 2329499855, 2024987596, 1809983544, 2575936315, 1296289744, 3207089363, 2893594407, 1578318884, 274646895, 3795141740, 4049975192, 51262619, 3619967088, 632279923, 922689671, 3298075524, 2592579488, 1760304291, 2075979607, 2312596564, 1562183871, 2943781820, 3156637768, 1313733451, 549293790, 3537243613, 3246849577, 871202090, 3878099393, 357341890, 102525238, 4101499445, 2858735121, 1477399826, 1264559846, 3107202533, 1845379342, 2677391885, 2361733625, 2125378298, 820201905, 3263744690, 3520608582, 598981189, 4151959214, 85089709, 373468761, 3827903834, 3124367742, 1213305469, 1526817161, 2842354314, 2107672161, 2412447074, 2627466902, 1861252501, 1098587580, 3004210879, 2688576843, 1378610760, 2262928035, 1955203488, 1742404180, 2511436119, 3416409459, 969524848, 714683780, 3639785095, 205050476, 4266873199, 3976438427, 526918040, 1361435347, 2739821008, 2954799652, 1114974503, 2529119692, 1691668175, 2005155131, 2247081528, 3690758684, 697762079, 986182379, 3366744552, 476452099, 3993867776, 4250756596, 255256311, 1640403810, 2477592673, 2164122517, 1922457750, 2791048317, 1412925310, 1197962378, 3037525897, 3944729517, 427051182, 170179418, 4165941337, 746937522, 3740196785, 3451792453, 1070968646, 1905808397, 2213795598, 2426610938, 1657317369, 3053634322, 1147748369, 1463399397, 2773627110, 4215344322, 153784257, 444234805, 3893493558, 1021025245, 3467647198, 3722505002, 797665321, 2197175160, 1889384571, 1674398607, 2443626636, 1164749927, 3070701412, 2757221520, 1446797203, 137323447, 4198817972, 3910406976, 461344835, 3484808360, 1037989803, 781091935, 3705997148, 2460548119, 1623424788, 1939049696, 2180517859, 1429367560, 2807687179, 3020495871, 1180866812, 410100952, 3927582683, 4182430767, 186734380, 3756733383, 763408580, 1053836080, 3434856499, 2722870694, 1344288421, 1131464017, 2971354706, 1708204729, 2545590714, 2229949006, 1988219213, 680717673, 3673779818, 3383336350, 1002577565, 4010310262, 493091189, 238226049, 4233660802, 2987750089, 1082061258, 1395524158, 2705686845, 1972364758, 2279892693, 2494862625, 1725896226, 952904198, 3399985413, 3656866545, 731699698, 4283874585, 222117402, 510512622, 3959836397, 3280807620, 837199303, 582374963, 3504198960, 68661723, 4135334616, 3844915500, 390545967, 1230274059, 3141532936, 2825850620, 1510247935, 2395924756, 2091215383, 1878366691, 2644384480, 3553878443, 565732008, 854102364, 3229815391, 340358836, 3861050807, 4117890627, 119113024, 1493875044, 2875275879, 3090270611, 1247431312, 2660249211, 1828433272, 2141937292, 2378227087, 3811616794, 291187481, 34330861, 4032846830, 615137029, 3603020806, 3314634738, 939183345, 1776939221, 2609017814, 2295496738, 2058945313, 2926798794, 1545135305, 1330124605, 3173225534, 4084100981, 17165430, 307568514, 3762199681, 888469610, 3332340585, 3587147933, 665062302, 2042050490, 2346497209, 2559330125, 1793573966, 3190661285, 1279665062, 1595330642, 2910671697];
Ported from
Functions
function RETRYABLE_ERR_FN_DEFAULT
RETRYABLE_ERR_FN_DEFAULT: (err?: ApiError) => boolean;
Returns true if the API request should be retried, given the error that was given the first time the request was attempted.
Parameter err
The API error to check if it is appropriate to retry. {boolean} True if the API request should be retried, false otherwise.
Classes
class ApiError
class ApiError extends Error {}
Custom error type for API errors.
Parameter errorBody
Error object.
constructor
constructor(errorMessage: string);
constructor
constructor(errorBody: GoogleErrorBody);
property code
code?: number;
property errors
errors?: GoogleInnerError[];
property response
response?: r.Response;
method createMultiErrorMessage
static createMultiErrorMessage: ( err: GoogleErrorBody, errors?: GoogleInnerError[]) => string;
Pieces together an error message by combining all unique error messages returned from a single GoogleError
Parameter err
The original error.
Parameter errors
Inner errors, if any.
Returns
{string}
class Bucket
class Bucket extends ServiceObject<Bucket, BucketMetadata> {}
Create a Bucket object to interact with a Cloud Storage bucket.
Parameter storage
A Storage instance.
Parameter name
The name of the bucket.
Parameter options
Configuration object.
Parameter
{string} [options.userProject] User project.
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const bucket = storage.bucket('albums');
constructor
constructor(storage: Storage, name: string, options?: BucketOptions);
property acl
acl: Acl;
property cloudStorageURI
readonly cloudStorageURI: URL;
The bucket's Cloud Storage URI (
gs://
)Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const bucket = storage.bucket('my-bucket');// `gs://my-bucket`const href = bucket.cloudStorageURI.href;
property crc32cGenerator
crc32cGenerator: CRC32CValidatorGenerator;
property iam
iam: Iam;
property instancePreconditionOpts
instancePreconditionOpts?: PreconditionOptions;
property name
name: string;
property signer
signer?: URLSigner;
property storage
storage: Storage;
property userProject
userProject?: string;
A user project to apply to each request from this bucket. Bucket#userProject {string}
method addLifecycleRule
addLifecycleRule: { ( rule: LifecycleRule | LifecycleRule[], options?: AddLifecycleRuleOptions ): Promise<SetBucketMetadataResponse>; ( rule: LifecycleRule | LifecycleRule[], options: AddLifecycleRuleOptions, callback: SetBucketMetadataCallback ): void; ( rule: LifecycleRule | LifecycleRule[], callback: SetBucketMetadataCallback ): void;};
method combine
combine: { ( sources: string[] | File[], destination: string | File, options?: CombineOptions ): Promise<CombineResponse>; ( sources: string[] | File[], destination: string | File, options: CombineOptions, callback: CombineCallback ): void; ( sources: string[] | File[], destination: string | File, callback: CombineCallback ): void;};
method createChannel
createChannel: { ( id: string, config: CreateChannelConfig, options?: CreateChannelOptions ): Promise<CreateChannelResponse>; ( id: string, config: CreateChannelConfig, callback: CreateChannelCallback ): void; ( id: string, config: CreateChannelConfig, options: CreateChannelOptions, callback: CreateChannelCallback ): void;};
method createNotification
createNotification: { ( topic: string, options?: CreateNotificationOptions ): Promise<CreateNotificationResponse>; ( topic: string, options: CreateNotificationOptions, callback: CreateNotificationCallback ): void; (topic: string, callback: CreateNotificationCallback): void;};
method deleteFiles
deleteFiles: { (query?: DeleteFilesOptions): Promise<void>; (callback: DeleteFilesCallback): void; (query: DeleteFilesOptions, callback: DeleteFilesCallback): void;};
method deleteLabels
deleteLabels: { (labels?: string | string[]): Promise<DeleteLabelsResponse>; (options: PreconditionOptions): Promise<DeleteLabelsResponse>; (callback: SetLabelsCallback): void; ( labels: string | string[], options: PreconditionOptions ): Promise<DeleteLabelsResponse>; (labels: string | string[], callback: SetLabelsCallback): void; ( labels: string | string[], options: PreconditionOptions, callback: SetLabelsCallback ): void;};
method disableAutoRetryConditionallyIdempotent_
disableAutoRetryConditionallyIdempotent_: ( coreOpts: any, methodType: AvailableServiceObjectMethods, localPreconditionOptions?: PreconditionOptions) => void;
method disableRequesterPays
disableRequesterPays: { ( options?: DisableRequesterPaysOptions ): Promise<DisableRequesterPaysResponse>; (callback: DisableRequesterPaysCallback): void; (options: PreconditionOptions, callback: DisableRequesterPaysCallback): void;};
method enableLogging
enableLogging: { (config: EnableLoggingOptions): Promise<SetBucketMetadataResponse>; (config: EnableLoggingOptions, callback: SetBucketMetadataCallback): void;};
method enableRequesterPays
enableRequesterPays: { (options?: EnableRequesterPaysOptions): Promise<EnableRequesterPaysResponse>; (callback: EnableRequesterPaysCallback): void; (options: PreconditionOptions, callback: EnableRequesterPaysCallback): void;};
method file
file: (name: string, options?: FileOptions) => File;
Create a File object. See File to see how to handle the different use cases you may have.
Parameter name
The name of the file in this bucket.
Parameter options
Configuration options.
Parameter
{string|number} [options.generation] Only use a specific revision of this file.
Parameter
{string} [options.encryptionKey] A custom encryption key. See Customer-supplied Encryption Keys.
Parameter
{string} [options.kmsKeyName] The name of the Cloud KMS key that will be used to encrypt the object. Must be in the format:
projects/my-project/locations/location/keyRings/my-kr/cryptoKeys/my-key
. KMS key ring must use the same location as the bucket.Parameter
{string} [options.userProject] The ID of the project which will be billed for all requests made from File object.
Returns
{File}
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const bucket = storage.bucket('albums');const file = bucket.file('my-existing-file.png');
method getFiles
getFiles: { (query?: GetFilesOptions): Promise<GetFilesResponse>; (query: GetFilesOptions, callback: GetFilesCallback): void; (callback: GetFilesCallback): void;};
method getFilesStream
getFilesStream: (query?: GetFilesOptions) => Readable;
method getId
getId: () => string;
method getLabels
getLabels: { (options?: GetLabelsOptions): Promise<GetLabelsResponse>; (callback: GetLabelsCallback): void; (options: GetLabelsOptions, callback: GetLabelsCallback): void;};
method getNotifications
getNotifications: { (options?: GetNotificationsOptions): Promise<GetNotificationsResponse>; (callback: GetNotificationsCallback): void; (options: GetNotificationsOptions, callback: GetNotificationsCallback): void;};
method getSignedUrl
getSignedUrl: { (cfg: GetBucketSignedUrlConfig): Promise<GetSignedUrlResponse>; (cfg: GetBucketSignedUrlConfig, callback: GetSignedUrlCallback): void;};
method lock
lock: { (metageneration: number | string): Promise<BucketLockResponse>; (metageneration: string | number, callback: BucketLockCallback): void;};
method makeAllFilesPublicPrivate_
makeAllFilesPublicPrivate_: { ( options?: MakeAllFilesPublicPrivateOptions ): Promise<MakeAllFilesPublicPrivateResponse>; (callback: MakeAllFilesPublicPrivateCallback): void; ( options: MakeAllFilesPublicPrivateOptions, callback: MakeAllFilesPublicPrivateCallback ): void;};
method makePrivate
makePrivate: { (options?: MakeBucketPrivateOptions): Promise<MakeBucketPrivateResponse>; (callback: MakeBucketPrivateCallback): void; ( options: MakeBucketPrivateOptions, callback: MakeBucketPrivateCallback ): void;};
method makePublic
makePublic: { (options?: MakeBucketPublicOptions): Promise<MakeBucketPublicResponse>; (callback: MakeBucketPublicCallback): void; (options: MakeBucketPublicOptions, callback: MakeBucketPublicCallback): void;};
method notification
notification: (id: string) => Notification;
Get a reference to a Cloud Pub/Sub Notification.
Parameter id
ID of notification.
Returns
{Notification}
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const bucket = storage.bucket('my-bucket');const notification = bucket.notification('1');See Also
Notification
method removeRetentionPeriod
removeRetentionPeriod: { (options?: SetBucketMetadataOptions): Promise<SetBucketMetadataResponse>; (callback: SetBucketMetadataCallback): void; ( options: SetBucketMetadataOptions, callback: SetBucketMetadataCallback ): void;};
method request
request: { (reqOpts: DecorateRequestOptions): Promise<RequestResponse>; (reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void;};
method setCorsConfiguration
setCorsConfiguration: { ( corsConfiguration: Cors[], options?: SetBucketMetadataOptions ): Promise<SetBucketMetadataResponse>; (corsConfiguration: Cors[], callback: SetBucketMetadataCallback): void; ( corsConfiguration: Cors[], options: SetBucketMetadataOptions, callback: SetBucketMetadataCallback ): void;};
method setLabels
setLabels: { (labels: Labels, options?: SetLabelsOptions): Promise<SetLabelsResponse>; (labels: Labels, callback: SetLabelsCallback): void; ( labels: Labels, options: SetLabelsOptions, callback: SetLabelsCallback ): void;};
method setMetadata
setMetadata: { (metadata: BucketMetadata, options?: SetMetadataOptions): Promise< SetMetadataResponse<BucketMetadata> >; (metadata: BucketMetadata, callback: MetadataCallback<BucketMetadata>): void; ( metadata: BucketMetadata, options: object, callback: MetadataCallback<BucketMetadata> ): void;};
method setRetentionPeriod
setRetentionPeriod: { ( duration: number, options?: SetBucketMetadataOptions ): Promise<SetBucketMetadataResponse>; (duration: number, callback: SetBucketMetadataCallback): void; ( duration: number, options: SetBucketMetadataOptions, callback: SetBucketMetadataCallback ): void;};
method setStorageClass
setStorageClass: { ( storageClass: string, options?: SetBucketStorageClassOptions ): Promise<SetBucketMetadataResponse>; (storageClass: string, callback: SetBucketStorageClassCallback): void; ( storageClass: string, options: SetBucketStorageClassOptions, callback: SetBucketStorageClassCallback ): void;};
method setUserProject
setUserProject: (userProject: string) => void;
Set a user project to be billed for all requests made from this Bucket object and any files referenced from this Bucket object.
Parameter userProject
The user project.
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const bucket = storage.bucket('albums');bucket.setUserProject('grape-spaceship-123');
method upload
upload: { (pathString: string, options?: UploadOptions): Promise<UploadResponse>; (pathString: string, options: UploadOptions, callback: UploadCallback): void; (pathString: string, callback: UploadCallback): void;};
class Channel
class Channel extends ServiceObject<Channel, BaseMetadata> {}
Create a channel object to interact with a Cloud Storage channel.
Parameter id
The ID of the channel.
Parameter resourceId
The resource ID of the channel.
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const channel = storage.channel('id', 'resource-id');
constructor
constructor(storage: Storage, id: string, resourceId: string);
method stop
stop: { (): Promise<unknown>; (callback: StopCallback): void };
class CRC32C
class CRC32C implements CRC32CValidator {}
constructor
constructor(initialValue?: number);
Constructs a new
CRC32C
object.Reconstruction is recommended via the
CRC32C.from
static method.Parameter initialValue
An initial CRC32C value - a signed 32-bit integer.
property CRC32C_EXTENSION_TABLE
static readonly CRC32C_EXTENSION_TABLE: Int32Array;
property CRC32C_EXTENSIONS
static readonly CRC32C_EXTENSIONS: readonly [ 0, 4067132163, 3778769143, 324072436, 3348797215, 904991772, 648144872, 3570033899, 2329499855, 2024987596, 1809983544, 2575936315, 1296289744, 3207089363, 2893594407, 1578318884, 274646895, 3795141740, 4049975192, 51262619, 3619967088, 632279923, 922689671, 3298075524, 2592579488, 1760304291, 2075979607, 2312596564, 1562183871, 2943781820, 3156637768, 1313733451, 549293790, 3537243613, 3246849577, 871202090, 3878099393, 357341890, 102525238, 4101499445, 2858735121, 1477399826, 1264559846, 3107202533, 1845379342, 2677391885, 2361733625, 2125378298, 820201905, 3263744690, 3520608582, 598981189, 4151959214, 85089709, 373468761, 3827903834, 3124367742, 1213305469, 1526817161, 2842354314, 2107672161, 2412447074, 2627466902, 1861252501, 1098587580, 3004210879, 2688576843, 1378610760, 2262928035, 1955203488, 1742404180, 2511436119, 3416409459, 969524848, 714683780, 3639785095, 205050476, 4266873199, 3976438427, 526918040, 1361435347, 2739821008, 2954799652, 1114974503, 2529119692, 1691668175, 2005155131, 2247081528, 3690758684, 697762079, 986182379, 3366744552, 476452099, 3993867776, 4250756596, 255256311, 1640403810, 2477592673, 2164122517, 1922457750, 2791048317, 1412925310, 1197962378, 3037525897, 3944729517, 427051182, 170179418, 4165941337, 746937522, 3740196785, 3451792453, 1070968646, 1905808397, 2213795598, 2426610938, 1657317369, 3053634322, 1147748369, 1463399397, 2773627110, 4215344322, 153784257, 444234805, 3893493558, 1021025245, 3467647198, 3722505002, 797665321, 2197175160, 1889384571, 1674398607, 2443626636, 1164749927, 3070701412, 2757221520, 1446797203, 137323447, 4198817972, 3910406976, 461344835, 3484808360, 1037989803, 781091935, 3705997148, 2460548119, 1623424788, 1939049696, 2180517859, 1429367560, 2807687179, 3020495871, 1180866812, 410100952, 3927582683, 4182430767, 186734380, 3756733383, 763408580, 1053836080, 3434856499, 2722870694, 1344288421, 1131464017, 2971354706, 1708204729, 2545590714, 2229949006, 1988219213, 680717673, 3673779818, 3383336350, 1002577565, 4010310262, 493091189, 238226049, 4233660802, 2987750089, 1082061258, 1395524158, 2705686845, 1972364758, 2279892693, 2494862625, 1725896226, 952904198, 3399985413, 3656866545, 731699698, 4283874585, 222117402, 510512622, 3959836397, 3280807620, 837199303, 582374963, 3504198960, 68661723, 4135334616, 3844915500, 390545967, 1230274059, 3141532936, 2825850620, 1510247935, 2395924756, 2091215383, 1878366691, 2644384480, 3553878443, 565732008, 854102364, 3229815391, 340358836, 3861050807, 4117890627, 119113024, 1493875044, 2875275879, 3090270611, 1247431312, 2660249211, 1828433272, 2141937292, 2378227087, 3811616794, 291187481, 34330861, 4032846830, 615137029, 3603020806, 3314634738, 939183345, 1776939221, 2609017814, 2295496738, 2058945313, 2926798794, 1545135305, 1330124605, 3173225534, 4084100981, 17165430, 307568514, 3762199681, 888469610, 3332340585, 3587147933, 665062302, 2042050490, 2346497209, 2559330125, 1793573966, 3190661285, 1279665062, 1595330642, 2910671697];
method from
static from: ( value: ArrayBuffer | ArrayBufferView | CRC32CValidator | string | number) => CRC32C;
Generates a
CRC32C
from a variety of compatable types. Note: strings are treated as input, not as file paths to read from.Parameter value
A number, 4-byte
ArrayBufferView
/Buffer
/TypedArray
, or 4-byte base64-encoded data (string)
method fromFile
static fromFile: (file: PathLike) => Promise<CRC32C>;
method toBuffer
toBuffer: () => Buffer;
Returns a
Buffer
representation of the CRC32C value
method toJSON
toJSON: () => string;
Returns a JSON-compatible, base64-encoded representation of the CRC32C value.
See
method toString
toString: () => string;
Returns a base64-encoded representation of the CRC32C value.
See
method update
update: (data: Buffer) => void;
Calculates a CRC32C from a provided buffer.
Implementation inspired from: - - -
Parameter data
The
Buffer
to generate the CRC32C from
method validate
validate: (input: Buffer | CRC32CValidator | string | number) => boolean;
Validates a provided input to the current CRC32C value.
Parameter input
A Buffer,
CRC32C
-compatible object, base64-encoded data (string), or signed 32-bit integer
method valueOf
valueOf: () => number;
Returns the
number
representation of the CRC32C value as a signed 32-bit integerSee
class File
class File extends ServiceObject<File, FileMetadata> {}
A File object is created from your Bucket object using Bucket#file.
constructor
constructor(bucket: Bucket, name: string, options?: FileOptions);
Constructs a file object.
Parameter bucket
The Bucket instance this file is attached to.
Parameter name
The name of the remote file.
Parameter options
Configuration options.
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const myBucket = storage.bucket('my-bucket');const file = myBucket.file('my-file');
property acl
acl: Acl;
property bucket
bucket: Bucket;
property cloudStorageURI
readonly cloudStorageURI: URL;
The object's Cloud Storage URI (
gs://
)Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const bucket = storage.bucket('my-bucket');const file = bucket.file('image.png');// `gs://my-bucket/image.png`const href = file.cloudStorageURI.href;
property crc32cGenerator
crc32cGenerator: CRC32CValidatorGenerator;
property generation
generation?: number;
property instancePreconditionOpts
instancePreconditionOpts?: PreconditionOptions;
property kmsKeyName
kmsKeyName?: string;
property name
name: string;
property parent
parent: Bucket;
property signer
signer?: URLSigner;
property storage
storage: Storage;
property userProject
userProject?: string;
method copy
copy: { ( destination: string | Bucket | File, options?: CopyOptions ): Promise<CopyResponse>; (destination: string | Bucket | File, callback: CopyCallback): void; ( destination: string | Bucket | File, options: CopyOptions, callback: CopyCallback ): void;};
method createReadStream
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.
NOTE: Readable streams will emit the
end
event when the file is fully downloaded.Parameter options
Configuration options.
Returns
{ReadableStream}
Example 1
//-// <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'));
method createResumableUpload
createResumableUpload: { ( options?: CreateResumableUploadOptions ): Promise<CreateResumableUploadResponse>; ( options: CreateResumableUploadOptions, callback: CreateResumableUploadCallback ): void; (callback: CreateResumableUploadCallback): void;};
method createWriteStream
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 setting
options.resumable
tofalse
.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.
NOTE: Writable streams will emit the
finish
event when the file is fully uploaded.See See
Parameter options
Configuration options.
Returns
{WritableStream}
Example 1
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.});//- // Continuing a Resumable Upload // // One can capture a
uri
from a resumable upload to reuse later. // Additionally, for validation, one can also capture and passcrc32c
. //- let uri: string | undefined = undefined; let resumeCRC32C: string | undefined = undefined;fs.createWriteStream() .on('uri', link => {uri = link}) .on('crc32', crc32c => {resumeCRC32C = crc32c});
// later... fs.createWriteStream({uri, resumeCRC32C});
method delete
delete: { (options?: DeleteOptions): Promise<[r.Response]>; (options: DeleteOptions, callback: DeleteCallback): void; (callback: DeleteCallback): void;};
Delete the object.
Parameter callback
The callback function.
Parameter
{?error} callback.err - An error returned while making this request.
Parameter
{object} callback.apiResponse - The full API response.
method disableAutoRetryConditionallyIdempotent_
disableAutoRetryConditionallyIdempotent_: ( coreOpts: any, methodType: AvailableServiceObjectMethods, localPreconditionOptions?: PreconditionOptions) => void;
method download
download: { (options?: DownloadOptions): Promise<DownloadResponse>; (options: DownloadOptions, callback: DownloadCallback): void; (callback: DownloadCallback): void;};
method from
static from: ( publicUrlOrGsUrl: string, storageInstance: Storage, options?: FileOptions) => File;
Gets a reference to a Cloud Storage File file from the provided URL in string format.
Parameter publicUrlOrGsUrl
the URL as a string. Must be of the format gs://bucket/file or https://storage.googleapis.com/bucket/file.
Parameter storageInstance
an instance of a Storage object.
Parameter options
Configuration options
Returns
{File}
method generateSignedPostPolicyV2
generateSignedPostPolicyV2: { ( options: GenerateSignedPostPolicyV2Options ): Promise<GenerateSignedPostPolicyV2Response>; ( options: GenerateSignedPostPolicyV2Options, callback: GenerateSignedPostPolicyV2Callback ): void; (callback: GenerateSignedPostPolicyV2Callback): void;};
method generateSignedPostPolicyV4
generateSignedPostPolicyV4: { ( options: GenerateSignedPostPolicyV4Options ): Promise<GenerateSignedPostPolicyV4Response>; ( options: GenerateSignedPostPolicyV4Options, callback: GenerateSignedPostPolicyV4Callback ): void; (callback: GenerateSignedPostPolicyV4Callback): void;};
method get
get: { (options?: GetFileOptions): Promise<GetResponse<File>>; (callback: InstanceResponseCallback<File>): void; (options: GetFileOptions, callback: InstanceResponseCallback<File>): void;};
method getExpirationDate
getExpirationDate: { (): Promise<GetExpirationDateResponse>; (callback: GetExpirationDateCallback): void;};
method getSignedUrl
getSignedUrl: { (cfg: GetSignedUrlConfig): Promise<GetSignedUrlResponse>; (cfg: GetSignedUrlConfig, callback: GetSignedUrlCallback): void;};
method isPublic
isPublic: { (): Promise<IsPublicResponse>; (callback: IsPublicCallback): void };
method makePrivate
makePrivate: { (options?: MakeFilePrivateOptions): Promise<MakeFilePrivateResponse>; (callback: SetFileMetadataCallback): void; (options: MakeFilePrivateOptions, callback: SetFileMetadataCallback): void;};
method makePublic
makePublic: { (): Promise<MakeFilePublicResponse>; (callback: MakeFilePublicCallback): void;};
method move
move: { ( destination: string | Bucket | File, options?: MoveOptions ): Promise<MoveResponse>; (destination: string | Bucket | File, callback: MoveCallback): void; ( destination: string | Bucket | File, options: MoveOptions, callback: MoveCallback ): void;};
method publicUrl
publicUrl: () => string;
The public URL of this File Use File#makePublic to enable anonymous access via the returned URL.
Returns
{string}
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();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();
method rename
rename: { ( destinationFile: string | File, options?: RenameOptions ): Promise<RenameResponse>; (destinationFile: string | File, callback: MoveCallback): void; ( destinationFile: string | File, options: MoveOptions, callback: MoveCallback ): void;};
method request
request: { (reqOpts: DecorateRequestOptions): Promise<RequestResponse>; (reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void;};
method restore
restore: (options: RestoreOptions) => Promise<File>;
Restores a soft-deleted file
Parameter options
Restore options.
Returns
{Promise}
method rotateEncryptionKey
rotateEncryptionKey: { (options?: RotateEncryptionKeyOptions): Promise<RotateEncryptionKeyResponse>; (callback: CopyCallback): void; (options: any, callback: CopyCallback): void;};
method save
save: { (data: SaveData, options?: SaveOptions): Promise<void>; (data: any, callback: SaveCallback): void; (data: any, options: SaveOptions, callback: SaveCallback): void;};
method setEncryptionKey
setEncryptionKey: (encryptionKey: string | Buffer) => this;
The Storage API allows you to use a custom key for server-side encryption.
Parameter encryptionKey
An AES-256 encryption key.
Returns
{File}
Example 1
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'});});});Example 2
include:samples/encryption.js region_tag:storage_upload_encrypted_file Example of uploading an encrypted file:
Example 3
include:samples/encryption.js region_tag:storage_download_encrypted_file Example of downloading an encrypted file:
method setMetadata
setMetadata: { (metadata: FileMetadata, options?: SetMetadataOptions): Promise< SetMetadataResponse<FileMetadata> >; (metadata: FileMetadata, callback: MetadataCallback<FileMetadata>): void; ( metadata: FileMetadata, options: object, callback: MetadataCallback<FileMetadata> ): void;};
method setStorageClass
setStorageClass: { ( storageClass: string, options?: SetStorageClassOptions ): Promise<SetStorageClassResponse>; ( storageClass: string, options: SetStorageClassOptions, callback: SetStorageClassCallback ): void; (storageClass: string, callback?: SetStorageClassCallback): void;};
method setUserProject
setUserProject: (userProject: string) => void;
Set a user project to be billed for all requests made from this File object.
Parameter userProject
The user project.
Example 1
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');
method startResumableUpload_
startResumableUpload_: ( dup: Duplexify, options?: CreateResumableUploadOptions) => void;
This creates a resumable-upload upload stream.
Parameter stream
Duplexify stream of data to pipe to the file.
Parameter options
Configuration object.
method startSimpleUpload_
startSimpleUpload_: (dup: Duplexify, options?: CreateWriteStreamOptions) => void;
Takes a readable stream and pipes it to a remote file. Unlike
startResumableUpload_
, which uses the resumable upload technique, this method uses a simple upload (all or nothing).Parameter dup
Duplexify stream of data to pipe to the file.
Parameter options
Configuration object.
class HashStreamValidator
class HashStreamValidator extends Transform {}
constructor
constructor(options?: Partial<HashStreamValidatorOptions>);
property crc32c
readonly crc32c: string;
Return the current CRC32C value, if available.
property crc32cEnabled
readonly crc32cEnabled: boolean;
property crc32cExpected
readonly crc32cExpected: string;
property md5Enabled
readonly md5Enabled: boolean;
property md5Expected
readonly md5Expected: string;
property updateHashesOnly
readonly updateHashesOnly: boolean;
method test
test: (hash: 'crc32c' | 'md5', sum: Buffer | string) => boolean;
class HmacKey
class HmacKey extends ServiceObject<HmacKey, HmacKeyMetadata> {}
An HmacKey object contains metadata of an HMAC key created from a service account through the Storage client using Storage#createHmacKey.
constructor
constructor(storage: Storage, accessId: string, options?: HmacKeyOptions);
Constructs an HmacKey object.
Note: this only create a local reference to an HMAC key, to create an HMAC key, use Storage#createHmacKey.
Parameter storage
The Storage instance this HMAC key is attached to.
Parameter accessId
The unique accessId for this HMAC key.
Parameter options
Constructor configurations.
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const hmacKey = storage.hmacKey('access-id');
property storage
storage: Storage;
method setMetadata
setMetadata: { (metadata: HmacKeyMetadata, options?: SetMetadataOptions): Promise< SetMetadataResponse<HmacKeyMetadata> >; ( metadata: HmacKeyMetadata, callback: MetadataCallback<HmacKeyMetadata> ): void; ( metadata: HmacKeyMetadata, options: object, callback: MetadataCallback<HmacKeyMetadata> ): void;};
Set the metadata for this object.
Parameter metadata
The metadata to set on this object.
Parameter options
Configuration options.
Parameter callback
The callback function.
Parameter
{?error} callback.err - An error returned while making this request.
Parameter
{object} callback.apiResponse - The full API response.
class Iam
class Iam {}
Get and set IAM policies for your Cloud Storage bucket.
See Cloud Storage IAM Management See Granting, Changing, and Revoking Access See IAM Roles
Iam
Parameter bucket
The parent instance.
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const bucket = storage.bucket('my-bucket');// bucket.iam
constructor
constructor(bucket: Bucket);
method getPolicy
getPolicy: { (options?: GetPolicyOptions): Promise<GetPolicyResponse>; (options: GetPolicyOptions, callback: GetPolicyCallback): void; (callback: GetPolicyCallback): void;};
method setPolicy
setPolicy: { (policy: Policy, options?: SetPolicyOptions): Promise<SetPolicyResponse>; (policy: Policy, callback: SetPolicyCallback): void; ( policy: Policy, options: SetPolicyOptions, callback: SetPolicyCallback ): void;};
method testPermissions
testPermissions: { ( permissions: string | string[], options?: TestIamPermissionsOptions ): Promise<TestIamPermissionsResponse>; (permissions: string | string[], callback: TestIamPermissionsCallback): void; ( permissions: string | string[], options: TestIamPermissionsOptions, callback: TestIamPermissionsCallback ): void;};
class MultiPartUploadError
class MultiPartUploadError extends Error {}
constructor
constructor(message: string, uploadId: string, partsMap: Map<number, string>);
class Notification
class Notification extends ServiceObject<Notification, NotificationMetadata> {}
A Notification object is created from your Bucket object using Bucket#notification. Use it to interact with Cloud Pub/Sub notifications.
See Cloud Pub/Sub Notifications for Google Cloud Storage
Parameter bucket
The bucket instance this notification is attached to.
Parameter id
The ID of the notification.
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const myBucket = storage.bucket('my-bucket');const notification = myBucket.notification('1');
constructor
constructor(bucket: Bucket, id: string);
class Storage
class Storage extends Service {}
ACLs Cloud Storage uses access control lists (ACLs) to manage object and bucket access. ACLs are the mechanism you use to share files with other users and allow other users to access your buckets and files.
To learn more about ACLs, read this overview on Access Control.
See Cloud Storage overview See Access Control
constructor
constructor(options?: StorageOptions);
Constructs the Storage client.
Parameter options
Configuration options.
Example 1
Create a client that uses Application Default Credentials (ADC)
const {Storage} = require('@google-cloud/storage');const storage = new Storage();Example 2
Create a client with explicit credentials
const storage = new Storage({projectId: 'your-project-id',keyFilename: '/path/to/keyfile.json'});Example 3
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',}});Example 4
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')});Example 5
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
property acl
static acl: { OWNER_ROLE: string; READER_ROLE: string; WRITER_ROLE: string };
property acl
acl: { OWNER_ROLE: string; READER_ROLE: string; WRITER_ROLE: string };
Reference to Storage.acl.
Storage#acl
See Also
Storage.acl
property Bucket
static Bucket: typeof Bucket;
Bucket class.
Storage.Bucket
See Also
Bucket {Constructor}
property Channel
static Channel: typeof Channel;
Channel class.
Storage.Channel
See Also
Channel {Constructor}
property crc32cGenerator
crc32cGenerator: CRC32CValidatorGenerator;
property File
static File: typeof File;
File class.
Storage.File
See Also
File {Constructor}
property HmacKey
static HmacKey: typeof HmacKey;
HmacKey class.
Storage.HmacKey
See Also
HmacKey {Constructor}
property retryOptions
retryOptions: RetryOptions;
method bucket
bucket: (name: string, options?: BucketOptions) => Bucket;
Get a reference to a Cloud Storage bucket.
Parameter name
Name of the bucket.
Parameter options
Configuration object.
Parameter
{string} [options.kmsKeyName] A Cloud KMS key that will be used to encrypt objects inserted into this bucket, if no encryption method is specified.
Parameter
{string} [options.userProject] User project to be billed for all requests made from this Bucket object.
Returns
{Bucket}
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const albums = storage.bucket('albums');const photos = storage.bucket('photos');See Also
Bucket
method channel
channel: (id: string, resourceId: string) => Channel;
Reference a channel to receive notifications about changes to your bucket.
Parameter id
The ID of the channel.
Parameter resourceId
The resource ID of the channel.
Returns
{Channel}
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const channel = storage.channel('id', 'resource-id');See Also
Channel
method createBucket
createBucket: { ( name: string, metadata?: CreateBucketRequest ): Promise<CreateBucketResponse>; (name: string, callback: BucketCallback): void; ( name: string, metadata: CreateBucketRequest, callback: BucketCallback ): void; ( name: string, metadata: CreateBucketRequest, callback: BucketCallback ): void;};
method createHmacKey
createHmacKey: { ( serviceAccountEmail: string, options?: CreateHmacKeyOptions ): Promise<CreateHmacKeyResponse>; (serviceAccountEmail: string, callback: CreateHmacKeyCallback): void; ( serviceAccountEmail: string, options: CreateHmacKeyOptions, callback: CreateHmacKeyCallback ): void;};
method getBuckets
getBuckets: { (options?: GetBucketsRequest): Promise<GetBucketsResponse>; (options: GetBucketsRequest, callback: GetBucketsCallback): void; (callback: GetBucketsCallback): void;};
method getBucketsStream
getBucketsStream: () => Readable;
method getHmacKeys
getHmacKeys: { (options?: GetHmacKeysOptions): Promise<GetHmacKeysResponse>; (callback: GetHmacKeysCallback): void; (options: GetHmacKeysOptions, callback: GetHmacKeysCallback): void;};
Retrieves a list of HMAC keys matching the criteria.
The authenticated user must have storage.hmacKeys.list permission for the project in which the key exists.
Parameter options
Configuration options.
Parameter callback
Callback function. {Promise}
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();storage.getHmacKeys(function(err, hmacKeys) {if (!err) {// hmacKeys is an array of HmacKey objects.}});//-// To control how many API requests are made and page through the results// manually, set `autoPaginate` to `false`.//-const callback = function(err, hmacKeys, nextQuery, apiResponse) {if (nextQuery) {// More results exist.storage.getHmacKeys(nextQuery, callback);}// The `metadata` property is populated for you with the metadata at the// time of fetching.hmacKeys[0].metadata;};storage.getHmacKeys({autoPaginate: false}, callback);//-// If the callback is omitted, we'll return a Promise.//-storage.getHmacKeys().then(function(data) {const hmacKeys = data[0];});
method getHmacKeysStream
getHmacKeysStream: () => Readable;
method getServiceAccount
getServiceAccount: { (options?: GetServiceAccountOptions): Promise<GetServiceAccountResponse>; (options?: GetServiceAccountOptions): Promise<GetServiceAccountResponse>; ( options: GetServiceAccountOptions, callback: GetServiceAccountCallback ): void; (callback: GetServiceAccountCallback): void;};
method hmacKey
hmacKey: (accessId: string, options?: HmacKeyOptions) => 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 theoptions
argument.Parameter accessId
The HMAC key's access ID.
Parameter options
HmacKey constructor options.
Returns
{HmacKey}
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const hmacKey = storage.hmacKey('ACCESS_ID');See Also
HmacKey
class TransferManager
class TransferManager {}
Create a TransferManager object to perform parallel transfer operations on a Cloud Storage bucket.
Parameter bucket
A Bucket instance
constructor
constructor(bucket: Bucket);
property bucket
bucket: Bucket;
method downloadFileInChunks
downloadFileInChunks: ( fileOrName: File | string, options?: DownloadFileInChunksOptions) => Promise<void | DownloadResponse>;
Download a large file in chunks utilizing parallel download operations. This is a convenience method that utilizes File#download to perform the download.
Parameter fileOrName
File to download.
Parameter options
Configuration options.
Returns
{Promise<void | DownloadResponse>}
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const bucket = storage.bucket('my-bucket');const transferManager = new TransferManager(bucket);//-// Download a large file in chunks utilizing parallel operations.//-const response = await transferManager.downloadFileInChunks(bucket.file('large-file.txt');// Your local directory now contains:// - "large-file.txt" (with the contents from my-bucket.large-file.txt)
method downloadManyFiles
downloadManyFiles: ( filesOrFolder: File[] | string[] | string, options?: DownloadManyFilesOptions) => Promise<void | DownloadResponse[]>;
Download multiple files in parallel to the local filesystem. This is a convenience method that utilizes File#download to perform the download.
Parameter filesOrFolder
An array of file name strings or file objects to be downloaded. If a string is provided this will be treated as a GCS prefix and all files with that prefix will be downloaded.
Parameter options
Configuration options. Setting options.prefix or options.stripPrefix or options.passthroughOptions.destination will cause the downloaded files to be written to the file system instead of being returned as a buffer.
Returns
{Promise<DownloadResponse[]>}
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const bucket = storage.bucket('my-bucket');const transferManager = new TransferManager(bucket);//-// Download multiple files in parallel.//-const response = await transferManager.downloadManyFiles(['file1.txt', 'file2.txt']);// The following files have been downloaded:// - "file1.txt" (with the contents from my-bucket.file1.txt)// - "file2.txt" (with the contents from my-bucket.file2.txt)const response = await transferManager.downloadManyFiles([bucket.File('file1.txt'), bucket.File('file2.txt')]);// The following files have been downloaded:// - "file1.txt" (with the contents from my-bucket.file1.txt)// - "file2.txt" (with the contents from my-bucket.file2.txt)const response = await transferManager.downloadManyFiles('test-folder');// All files with GCS prefix of 'test-folder' have been downloaded.
method uploadFileInChunks
uploadFileInChunks: ( filePath: string, options?: UploadFileInChunksOptions, generator?: MultiPartHelperGenerator) => Promise<GaxiosResponse | undefined>;
Upload a large file in chunks utilizing parallel upload opertions. If the upload fails, an uploadId and map containing all the successfully uploaded parts will be returned to the caller. These arguments can be used to resume the upload.
Parameter filePath
The path of the file to be uploaded
Parameter options
Configuration options.
Parameter generator
A function that will return a type that implements the MPU interface. Most users will not need to use this.
Returns
{Promise} If successful a promise resolving to void, otherwise a error containing the message, uploadid, and parts map.
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const bucket = storage.bucket('my-bucket');const transferManager = new TransferManager(bucket);//-// Upload a large file in chunks utilizing parallel operations.//-const response = await transferManager.uploadFileInChunks('large-file.txt');// Your bucket now contains:// - "large-file.txt"
method uploadManyFiles
uploadManyFiles: ( filePathsOrDirectory: string[] | string, options?: UploadManyFilesOptions) => Promise<UploadResponse[]>;
Upload multiple files in parallel to the bucket. This is a convenience method that utilizes Bucket#upload to perform the upload.
Parameter filePathsOrDirectory
An array of fully qualified paths to the files or a directory name. If a directory name is provided, the directory will be recursively walked and all files will be added to the upload list. to be uploaded to the bucket
Parameter options
Configuration options.
Returns
{Promise<UploadResponse[]>}
Example 1
const {Storage} = require('@google-cloud/storage');const storage = new Storage();const bucket = storage.bucket('my-bucket');const transferManager = new TransferManager(bucket);//-// Upload multiple files in parallel.//-const response = await transferManager.uploadManyFiles(['/local/path/file1.txt, 'local/path/file2.txt']);// Your bucket now contains:// - "local/path/file1.txt" (with the contents of '/local/path/file1.txt')// - "local/path/file2.txt" (with the contents of '/local/path/file2.txt')const response = await transferManager.uploadManyFiles('/local/directory');// Your bucket will now contain all files contained in '/local/directory' maintaining the subdirectory structure.
Interfaces
interface AccessControlObject
interface AccessControlObject {}
interface AclMetadata
interface AclMetadata extends BaseMetadata {}
property bucket
bucket?: string;
property domain
domain?: string;
property entity
entity?: string;
property entityId
entityId?: string;
property generation
generation?: string;
property object
object?: string;
property projectTeam
projectTeam?: { projectNumber?: string; team?: 'editors' | 'owners' | 'viewers';};
property role
role?: 'OWNER' | 'READER' | 'WRITER' | 'FULL_CONTROL';
index signature
[key: string]: unknown;
interface AclOptions
interface AclOptions {}
property pathPrefix
pathPrefix: string;
property request
request: ( reqOpts: DecorateRequestOptions, callback: BodyResponseCallback) => void;
interface AddAclCallback
interface AddAclCallback {}
call signature
( err: Error | null, acl?: AccessControlObject | null, apiResponse?: AclMetadata): void;
interface AddAclOptions
interface AddAclOptions {}
property entity
entity: string;
property generation
generation?: number;
property role
role: string;
property userProject
userProject?: string;
interface BucketCallback
interface BucketCallback {}
call signature
(err: Error | null, bucket?: Bucket | null, apiResponse?: unknown): void;
interface BucketExistsOptions
interface BucketExistsOptions extends GetConfig {}
property userProject
userProject?: string;
interface BucketLockCallback
interface BucketLockCallback {}
call signature
(err?: Error | null, apiResponse?: unknown): void;
interface BucketMetadata
interface BucketMetadata extends BaseMetadata {}
property acl
acl?: AclMetadata[] | null;
property autoclass
autoclass?: { enabled?: boolean; toggleTime?: string; terminalStorageClass?: string; terminalStorageClassUpdateTime?: string;};
property billing
billing?: { requesterPays?: boolean;};
property cors
cors?: Cors[];
property customPlacementConfig
customPlacementConfig?: { dataLocations?: string[];};
property defaultEventBasedHold
defaultEventBasedHold?: boolean;
property defaultObjectAcl
defaultObjectAcl?: AclMetadata[];
property encryption
encryption?: { defaultKmsKeyName?: string;} | null;
property hierarchicalNamespace
hierarchicalNamespace?: { enabled?: boolean;};
property iamConfiguration
iamConfiguration?: { publicAccessPrevention?: string; uniformBucketLevelAccess?: { enabled?: boolean; lockedTime?: string; };};
property labels
labels?: { [key: string]: string | null;};
property lifecycle
lifecycle?: { rule?: LifecycleRule[];} | null;
property location
location?: string;
property locationType
locationType?: string;
property logging
logging?: { logBucket?: string; logObjectPrefix?: string;};
property metageneration
metageneration?: string;
property name
name?: string;
property objectRetention
objectRetention?: { mode?: string;};
property owner
owner?: { entity?: string; entityId?: string;};
property projectNumber
projectNumber?: string | number;
property retentionPolicy
retentionPolicy?: { effectiveTime?: string; isLocked?: boolean; retentionPeriod?: string | number;} | null;
property rpo
rpo?: string;
property softDeletePolicy
softDeletePolicy?: { retentionDurationSeconds?: string | number; readonly effectiveTime?: string;};
property storageClass
storageClass?: string;
property timeCreated
timeCreated?: string;
property updated
updated?: string;
property versioning
versioning?: { enabled?: boolean;};
property website
website?: { mainPageSuffix?: string; notFoundPage?: string;};
interface BucketOptions
interface BucketOptions {}
property crc32cGenerator
crc32cGenerator?: CRC32CValidatorGenerator;
property kmsKeyName
kmsKeyName?: string;
property preconditionOpts
preconditionOpts?: PreconditionOptions;
property userProject
userProject?: string;
interface CombineCallback
interface CombineCallback {}
call signature
(err: Error | null, newFile: File | null, apiResponse: unknown): void;
interface CombineOptions
interface CombineOptions extends PreconditionOptions {}
property kmsKeyName
kmsKeyName?: string;
property userProject
userProject?: string;
interface CopyCallback
interface CopyCallback {}
call signature
(err: Error | null, file?: File | null, apiResponse?: unknown): void;
interface CopyOptions
interface CopyOptions {}
property cacheControl
cacheControl?: string;
property contentDisposition
contentDisposition?: string;
property contentEncoding
contentEncoding?: string;
property contentType
contentType?: string;
property destinationKmsKeyName
destinationKmsKeyName?: string;
property metadata
metadata?: { [key: string]: string | boolean | number | null;};
property preconditionOpts
preconditionOpts?: PreconditionOptions;
property predefinedAcl
predefinedAcl?: string;
property token
token?: string;
property userProject
userProject?: string;
interface CRC32CValidator
interface CRC32CValidator {}
An interface for CRC32C hashing and validation
property toString
toString: () => string;
A method returning the CRC32C as a base64-encoded string.
Example 1
Hashing the string 'data' should return 'rth90Q=='
const buffer = Buffer.from('data');crc32c.update(buffer);crc32c.toString(); // 'rth90Q=='
property update
update: (data: Buffer) => void;
A method for passing
Buffer
s for CRC32C generation.Example 1
Hashing buffers from 'some ' and 'text\n'
const buffer1 = Buffer.from('some ');crc32c.update(buffer1);const buffer2 = Buffer.from('text\n');crc32c.update(buffer2);crc32c.toString(); // 'DkjKuA=='
property validate
validate: (value: string) => boolean;
A method validating a base64-encoded CRC32C string.
Example 1
Should return
true
if the value matches,false
otherwiseconst buffer = Buffer.from('data');crc32c.update(buffer);crc32c.validate('DkjKuA=='); // falsecrc32c.validate('rth90Q=='); // true
interface CRC32CValidatorGenerator
interface CRC32CValidatorGenerator {}
A function that generates a CRC32C Validator
call signature
(): CRC32CValidator;
Should return a new, ready-to-use
CRC32CValidator
interface CreateBucketQuery
interface CreateBucketQuery {}
property enableObjectRetention
enableObjectRetention: boolean;
property predefinedAcl
predefinedAcl?: | 'authenticatedRead' | 'private' | 'projectPrivate' | 'publicRead' | 'publicReadWrite';
property predefinedDefaultObjectAcl
predefinedDefaultObjectAcl?: | 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead';
property project
project: string;
property projection
projection?: 'full' | 'noAcl';
property userProject
userProject: string;
interface CreateBucketRequest
interface CreateBucketRequest extends BucketMetadata {}
property archive
archive?: boolean;
property coldline
coldline?: boolean;
property dataLocations
dataLocations?: string[];
property dra
dra?: boolean;
property enableObjectRetention
enableObjectRetention?: boolean;
property multiRegional
multiRegional?: boolean;
property nearline
nearline?: boolean;
property predefinedAcl
predefinedAcl?: | 'authenticatedRead' | 'private' | 'projectPrivate' | 'publicRead' | 'publicReadWrite';
property predefinedDefaultObjectAcl
predefinedDefaultObjectAcl?: | 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead';
property projection
projection?: 'full' | 'noAcl';
property regional
regional?: boolean;
property requesterPays
requesterPays?: boolean;
property rpo
rpo?: string;
property standard
standard?: boolean;
property storageClass
storageClass?: string;
property userProject
userProject?: string;
property versioning
versioning?: Versioning;
interface CreateChannelCallback
interface CreateChannelCallback {}
call signature
(err: Error | null, channel: Channel | null, apiResponse: unknown): void;
interface CreateChannelConfig
interface CreateChannelConfig extends WatchAllOptions {}
property address
address: string;
interface CreateChannelOptions
interface CreateChannelOptions {}
property userProject
userProject?: string;
interface CreateHmacKeyCallback
interface CreateHmacKeyCallback {}
call signature
( err: Error | null, hmacKey?: HmacKey | null, secret?: string | null, apiResponse?: HmacKeyResourceResponse): void;
interface CreateHmacKeyOptions
interface CreateHmacKeyOptions {}
property projectId
projectId?: string;
property userProject
userProject?: string;
interface CreateNotificationCallback
interface CreateNotificationCallback {}
call signature
( err: Error | null, notification: Notification | null, apiResponse: unknown): void;
interface CreateNotificationOptions
interface CreateNotificationOptions {}
property customAttributes
customAttributes?: { [key: string]: string;};
property eventTypes
eventTypes?: string[];
property objectNamePrefix
objectNamePrefix?: string;
property payloadFormat
payloadFormat?: string;
property userProject
userProject?: string;
interface CreateReadStreamOptions
interface CreateReadStreamOptions {}
property [GCCL_GCS_CMD_KEY]
[GCCL_GCS_CMD_KEY]?: string;
property decompress
decompress?: boolean;
property end
end?: number;
property start
start?: number;
property userProject
userProject?: string;
property validation
validation?: 'md5' | 'crc32c' | false | true;
interface CreateResumableUploadCallback
interface CreateResumableUploadCallback {}
call signature
(err: Error | null, uri?: string): void;
interface CreateResumableUploadOptions
interface CreateResumableUploadOptions extends Pick<resumableUpload.UploadConfig, PublicResumableUploadOptions> {}
property [GCCL_GCS_CMD_KEY]
[GCCL_GCS_CMD_KEY]?: resumableUpload.UploadConfig[typeof GCCL_GCS_CMD_KEY];
property preconditionOpts
preconditionOpts?: PreconditionOptions;
property resumeCRC32C
resumeCRC32C?: Parameters<(typeof CRC32C)['from']>[0];
A CRC32C to resume from when continuing a previous upload. It is recommended to capture the
crc32c
event from previous upload sessions to provide in subsequent requests in order to accurately track the upload. This is **required** when validating a final portion of the uploaded object.See Also
CRC32C.from for possible values.
interface CreateWriteStreamOptions
interface CreateWriteStreamOptions extends CreateResumableUploadOptions {}
property contentType
contentType?: string;
property gzip
gzip?: string | boolean;
property resumable
resumable?: boolean;
property timeout
timeout?: number;
property validation
validation?: string | boolean;
interface DeleteBucketCallback
interface DeleteBucketCallback extends DeleteCallback {}
call signature
(err: Error | null, apiResponse: unknown): void;
interface DeleteBucketOptions
interface DeleteBucketOptions {}
property ignoreNotFound
ignoreNotFound?: boolean;
property userProject
userProject?: string;
interface DeleteFileCallback
interface DeleteFileCallback {}
call signature
(err: Error | null, apiResponse?: unknown): void;
interface DeleteFileOptions
interface DeleteFileOptions {}
property ignoreNotFound
ignoreNotFound?: boolean;
property userProject
userProject?: string;
interface DeleteFilesCallback
interface DeleteFilesCallback {}
call signature
(err: Error | Error[] | null, apiResponse?: object): void;
interface DeleteFilesOptions
interface DeleteFilesOptions extends GetFilesOptions, PreconditionOptions {}
property force
force?: boolean;
interface DeleteNotificationCallback
interface DeleteNotificationCallback {}
DeleteNotificationCallback
Parameter err
Request error, if any.
Parameter apiResponse
The full API response.
call signature
(err: Error | null, apiResponse?: unknown): void;
interface DeleteNotificationOptions
interface DeleteNotificationOptions {}
property userProject
userProject?: string;
interface DisableRequesterPaysCallback
interface DisableRequesterPaysCallback {}
call signature
(err?: Error | null, apiResponse?: object): void;
interface DownloadFileInChunksOptions
interface DownloadFileInChunksOptions {}
property chunkSizeBytes
chunkSizeBytes?: number;
property concurrencyLimit
concurrencyLimit?: number;
property destination
destination?: string;
property noReturnData
noReturnData?: boolean;
property validation
validation?: 'crc32c' | false;
interface DownloadManyFilesOptions
interface DownloadManyFilesOptions {}
property concurrencyLimit
concurrencyLimit?: number;
property passthroughOptions
passthroughOptions?: DownloadOptions;
property prefix
prefix?: string;
property stripPrefix
stripPrefix?: string;
interface DownloadOptions
interface DownloadOptions extends CreateReadStreamOptions {}
property destination
destination?: string;
interface EnableRequesterPaysCallback
interface EnableRequesterPaysCallback {}
call signature
(err?: Error | null, apiResponse?: unknown): void;
interface EncryptionKeyOptions
interface EncryptionKeyOptions {}
property encryptionKey
encryptionKey?: string | Buffer;
property kmsKeyName
kmsKeyName?: string;
property preconditionOpts
preconditionOpts?: PreconditionOptions;
interface FileExistsCallback
interface FileExistsCallback {}
call signature
(err: Error | null, exists?: boolean): void;
interface FileExistsOptions
interface FileExistsOptions {}
property userProject
userProject?: string;
interface FileMetadata
interface FileMetadata extends BaseMetadata {}
property acl
acl?: AclMetadata[] | null;
property bucket
bucket?: string;
property cacheControl
cacheControl?: string;
property componentCount
componentCount?: number;
property contentDisposition
contentDisposition?: string;
property contentEncoding
contentEncoding?: string;
property contentLanguage
contentLanguage?: string;
property contentType
contentType?: string;
property crc32c
crc32c?: string;
property customerEncryption
customerEncryption?: { encryptionAlgorithm?: string; keySha256?: string;};
property customTime
customTime?: string;
property eventBasedHold
eventBasedHold?: boolean | null;
property eventBasedHoldReleaseTime
readonly eventBasedHoldReleaseTime?: string;
property generation
generation?: string | number;
property hardDeleteTime
hardDeleteTime?: string;
property kmsKeyName
kmsKeyName?: string;
property md5Hash
md5Hash?: string;
property mediaLink
mediaLink?: string;
property metadata
metadata?: { [key: string]: string | boolean | number | null;};
property metageneration
metageneration?: string | number;
property name
name?: string;
property owner
owner?: { entity?: string; entityId?: string;};
property retention
retention?: { retainUntilTime?: string; mode?: string;} | null;
property retentionExpirationTime
retentionExpirationTime?: string;
property size
size?: string | number;
property softDeleteTime
softDeleteTime?: string;
property storageClass
storageClass?: string;
property temporaryHold
temporaryHold?: boolean | null;
property timeCreated
timeCreated?: string;
property timeDeleted
timeDeleted?: string;
property timeStorageClassUpdated
timeStorageClassUpdated?: string;
property updated
updated?: string;
interface FileOptions
interface FileOptions {}
property crc32cGenerator
crc32cGenerator?: CRC32CValidatorGenerator;
property encryptionKey
encryptionKey?: string | Buffer;
property generation
generation?: number | string;
property kmsKeyName
kmsKeyName?: string;
property preconditionOpts
preconditionOpts?: PreconditionOptions;
property userProject
userProject?: string;
interface GenerateSignedPostPolicyV2Callback
interface GenerateSignedPostPolicyV2Callback {}
call signature
(err: Error | null, policy?: PolicyDocument): void;
interface GenerateSignedPostPolicyV2Options
interface GenerateSignedPostPolicyV2Options {}
property acl
acl?: string;
property contentLengthRange
contentLengthRange?: { min?: number; max?: number;};
property equals
equals?: string[] | string[][];