Spaces:
Sleeping
Sleeping
File size: 35,050 Bytes
de5ba48 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 | /// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
/// <reference types="node" />
import { BodyResponseCallback, DecorateRequestOptions, GetConfig, Metadata, MetadataCallback, ServiceObject, SetMetadataResponse } from './nodejs-common';
import { Writable, Readable } from 'stream';
import * as http from 'http';
import { PreconditionOptions, Storage } from './storage';
import { AvailableServiceObjectMethods, Bucket } from './bucket';
import { Acl } from './acl';
import { GetSignedUrlResponse, GetSignedUrlCallback, URLSigner, Query } from './signer';
import { ResponseBody, Duplexify } from './nodejs-common/util';
import { CRC32CValidatorGenerator } from './crc32c';
import { URL } from 'url';
import { DeleteCallback, DeleteOptions, SetMetadataOptions } from './nodejs-common/service-object';
import * as r from 'teeny-request';
export type GetExpirationDateResponse = [Date];
export interface GetExpirationDateCallback {
(err: Error | null, expirationDate?: Date | null, apiResponse?: Metadata): void;
}
export interface PolicyDocument {
string: string;
base64: string;
signature: string;
}
export type GenerateSignedPostPolicyV2Response = [PolicyDocument];
export interface GenerateSignedPostPolicyV2Callback {
(err: Error | null, policy?: PolicyDocument): void;
}
export interface GenerateSignedPostPolicyV2Options {
equals?: string[] | string[][];
expires: string | number | Date;
startsWith?: string[] | string[][];
acl?: string;
successRedirect?: string;
successStatus?: string;
contentLengthRange?: {
min?: number;
max?: number;
};
}
export interface PolicyFields {
[key: string]: string;
}
export interface GenerateSignedPostPolicyV4Options {
expires: string | number | Date;
bucketBoundHostname?: string;
virtualHostedStyle?: boolean;
conditions?: object[];
fields?: PolicyFields;
}
export interface GenerateSignedPostPolicyV4Callback {
(err: Error | null, output?: SignedPostPolicyV4Output): void;
}
export type GenerateSignedPostPolicyV4Response = [SignedPostPolicyV4Output];
export interface SignedPostPolicyV4Output {
url: string;
fields: PolicyFields;
}
export interface GetSignedUrlConfig {
action: 'read' | 'write' | 'delete' | 'resumable';
version?: 'v2' | 'v4';
virtualHostedStyle?: boolean;
cname?: string;
contentMd5?: string;
contentType?: string;
expires: string | number | Date;
accessibleAt?: string | number | Date;
extensionHeaders?: http.OutgoingHttpHeaders;
promptSaveAs?: string;
responseDisposition?: string;
responseType?: string;
queryParams?: Query;
}
export interface GetFileMetadataOptions {
userProject?: string;
}
export type GetFileMetadataResponse = [Metadata, Metadata];
export interface GetFileMetadataCallback {
(err: Error | null, metadata?: Metadata, apiResponse?: Metadata): void;
}
export interface GetFileOptions extends GetConfig {
userProject?: string;
}
export type GetFileResponse = [File, Metadata];
export interface GetFileCallback {
(err: Error | null, file?: File, apiResponse?: Metadata): void;
}
export interface FileExistsOptions {
userProject?: string;
}
export type FileExistsResponse = [boolean];
export interface FileExistsCallback {
(err: Error | null, exists?: boolean): void;
}
export interface DeleteFileOptions {
ignoreNotFound?: boolean;
userProject?: string;
}
export type DeleteFileResponse = [Metadata];
export interface DeleteFileCallback {
(err: Error | null, apiResponse?: Metadata): void;
}
export type PredefinedAcl = 'authenticatedRead' | 'bucketOwnerFullControl' | 'bucketOwnerRead' | 'private' | 'projectPrivate' | 'publicRead';
export interface CreateResumableUploadOptions {
chunkSize?: number;
highWaterMark?: number;
metadata?: Metadata;
origin?: string;
offset?: number;
predefinedAcl?: PredefinedAcl;
private?: boolean;
public?: boolean;
uri?: string;
userProject?: string;
preconditionOpts?: PreconditionOptions;
}
export type CreateResumableUploadResponse = [string];
export interface CreateResumableUploadCallback {
(err: Error | null, uri?: string): void;
}
export interface CreateWriteStreamOptions extends CreateResumableUploadOptions {
contentType?: string;
gzip?: string | boolean;
resumable?: boolean;
timeout?: number;
validation?: string | boolean;
}
export interface MakeFilePrivateOptions {
metadata?: Metadata;
strict?: boolean;
userProject?: string;
preconditionOpts?: PreconditionOptions;
}
export type MakeFilePrivateResponse = [Metadata];
export type MakeFilePrivateCallback = SetFileMetadataCallback;
export interface IsPublicCallback {
(err: Error | null, resp?: boolean): void;
}
export type IsPublicResponse = [boolean];
export type MakeFilePublicResponse = [Metadata];
export interface MakeFilePublicCallback {
(err?: Error | null, apiResponse?: Metadata): void;
}
export type MoveResponse = [Metadata];
export interface MoveCallback {
(err: Error | null, destinationFile?: File | null, apiResponse?: Metadata): void;
}
export interface MoveOptions {
userProject?: string;
preconditionOpts?: PreconditionOptions;
}
export type RenameOptions = MoveOptions;
export type RenameResponse = MoveResponse;
export type RenameCallback = MoveCallback;
export type RotateEncryptionKeyOptions = string | Buffer | EncryptionKeyOptions;
export interface EncryptionKeyOptions {
encryptionKey?: string | Buffer;
kmsKeyName?: string;
preconditionOpts?: PreconditionOptions;
}
export type RotateEncryptionKeyCallback = CopyCallback;
export type RotateEncryptionKeyResponse = CopyResponse;
export declare enum ActionToHTTPMethod {
read = "GET",
write = "PUT",
delete = "DELETE",
resumable = "POST"
}
/**
* @private
*/
export declare const STORAGE_POST_POLICY_BASE_URL = "https://storage.googleapis.com";
export interface FileOptions {
crc32cGenerator?: CRC32CValidatorGenerator;
encryptionKey?: string | Buffer;
generation?: number | string;
kmsKeyName?: string;
preconditionOpts?: PreconditionOptions;
userProject?: string;
}
export interface CopyOptions {
cacheControl?: string;
contentEncoding?: string;
contentType?: string;
contentDisposition?: string;
destinationKmsKeyName?: string;
metadata?: Metadata;
predefinedAcl?: string;
token?: string;
userProject?: string;
preconditionOpts?: PreconditionOptions;
}
export type CopyResponse = [File, Metadata];
export interface CopyCallback {
(err: Error | null, file?: File | null, apiResponse?: Metadata): void;
}
export type DownloadResponse = [Buffer];
export type DownloadCallback = (err: RequestError | null, contents: Buffer) => void;
export interface DownloadOptions extends CreateReadStreamOptions {
destination?: string;
}
export interface CreateReadStreamOptions {
userProject?: string;
validation?: 'md5' | 'crc32c' | false | true;
start?: number;
end?: number;
decompress?: boolean;
}
export interface SaveOptions extends CreateWriteStreamOptions {
onUploadProgress?: (progressEvent: any) => void;
}
export interface SaveCallback {
(err?: Error | null): void;
}
export interface SetFileMetadataOptions {
userProject?: string;
}
export interface SetFileMetadataCallback {
(err?: Error | null, apiResponse?: Metadata): void;
}
export type SetFileMetadataResponse = [Metadata];
export type SetStorageClassResponse = [Metadata];
export interface SetStorageClassOptions {
userProject?: string;
preconditionOpts?: PreconditionOptions;
}
export interface SetStorageClassCallback {
(err?: Error | null, apiResponse?: Metadata): void;
}
export declare class RequestError extends Error {
code?: string;
errors?: Error[];
}
export declare enum FileExceptionMessages {
EXPIRATION_TIME_NA = "An expiration time is not available.",
DESTINATION_NO_NAME = "Destination file should have a name.",
INVALID_VALIDATION_FILE_RANGE = "Cannot use validation with file ranges (start/end).",
MD5_NOT_AVAILABLE = "MD5 verification was specified, but is not available for the requested object. MD5 is not available for composite objects.",
EQUALS_CONDITION_TWO_ELEMENTS = "Equals condition must be an array of 2 elements.",
STARTS_WITH_TWO_ELEMENTS = "StartsWith condition must be an array of 2 elements.",
CONTENT_LENGTH_RANGE_MIN_MAX = "ContentLengthRange must have numeric min & max fields.",
DOWNLOAD_MISMATCH = "The downloaded data did not match the data from the server. To be sure the content is the same, you should download the file again.",
UPLOAD_MISMATCH_DELETE_FAIL = "The uploaded data did not match the data from the server.\n As a precaution, we attempted to delete the file, but it was not successful.\n To be sure the content is the same, you should try removing the file manually,\n then uploading the file again.\n \n\nThe delete attempt failed with this message:\n\n ",
UPLOAD_MISMATCH = "The uploaded data did not match the data from the server.\n As a precaution, the file has been deleted.\n To be sure the content is the same, you should try uploading the file again."
}
/**
* A File object is created from your {@link Bucket} object using
* {@link Bucket#file}.
*
* @class
*/
declare class File extends ServiceObject<File> {
#private;
acl: Acl;
crc32cGenerator: CRC32CValidatorGenerator;
bucket: Bucket;
storage: Storage;
kmsKeyName?: string;
userProject?: string;
signer?: URLSigner;
metadata: Metadata;
name: string;
generation?: number;
parent: Bucket;
private encryptionKey?;
private encryptionKeyBase64?;
private encryptionKeyHash?;
private encryptionKeyInterceptor?;
private instanceRetryValue?;
instancePreconditionOpts?: PreconditionOptions;
/**
* Cloud Storage uses access control lists (ACLs) to manage object and
* bucket access. ACLs are the mechanism you use to share objects with other
* users and allow other users to access your buckets and objects.
*
* An ACL consists of one or more entries, where each entry grants permissions
* to an entity. Permissions define the actions that can be performed against
* an object or bucket (for example, `READ` or `WRITE`); the entity defines
* who the permission applies to (for example, a specific user or group of
* users).
*
* The `acl` object on a File instance provides methods to get you a list of
* the ACLs defined on your bucket, as well as set, update, and delete them.
*
* See {@link http://goo.gl/6qBBPO| About Access Control lists}
*
* @name File#acl
* @mixes Acl
*
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const myBucket = storage.bucket('my-bucket');
*
* const file = myBucket.file('my-file');
* //-
* // Make a file publicly readable.
* //-
* const options = {
* entity: 'allUsers',
* role: storage.acl.READER_ROLE
* };
*
* file.acl.add(options, function(err, aclObject) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* file.acl.add(options).then(function(data) {
* const aclObject = data[0];
* const apiResponse = data[1];
* });
* ```
*/
/**
* The API-formatted resource description of the file.
*
* Note: This is not guaranteed to be up-to-date when accessed. To get the
* latest record, call the `getMetadata()` method.
*
* @name File#metadata
* @type {object}
*/
/**
* The file's name.
* @name File#name
* @type {string}
*/
/**
* @callback Crc32cGeneratorToStringCallback
* A method returning the CRC32C as a base64-encoded string.
*
* @returns {string}
*
* @example
* Hashing the string 'data' should return 'rth90Q=='
*
* ```js
* const buffer = Buffer.from('data');
* crc32c.update(buffer);
* crc32c.toString(); // 'rth90Q=='
* ```
**/
/**
* @callback Crc32cGeneratorValidateCallback
* A method validating a base64-encoded CRC32C string.
*
* @param {string} [value] base64-encoded CRC32C string to validate
* @returns {boolean}
*
* @example
* Should return `true` if the value matches, `false` otherwise
*
* ```js
* const buffer = Buffer.from('data');
* crc32c.update(buffer);
* crc32c.validate('DkjKuA=='); // false
* crc32c.validate('rth90Q=='); // true
* ```
**/
/**
* @callback Crc32cGeneratorUpdateCallback
* A method for passing `Buffer`s for CRC32C generation.
*
* @param {Buffer} [data] data to update CRC32C value with
* @returns {undefined}
*
* @example
* Hashing buffers from 'some ' and 'text\n'
*
* ```js
* const buffer1 = Buffer.from('some ');
* crc32c.update(buffer1);
*
* const buffer2 = Buffer.from('text\n');
* crc32c.update(buffer2);
*
* crc32c.toString(); // 'DkjKuA=='
* ```
**/
/**
* @typedef {object} CRC32CValidator
* @property {Crc32cGeneratorToStringCallback}
* @property {Crc32cGeneratorValidateCallback}
* @property {Crc32cGeneratorUpdateCallback}
*/
/**
* @callback Crc32cGeneratorCallback
* @returns {CRC32CValidator}
*/
/**
* @typedef {object} FileOptions Options passed to the File constructor.
* @property {string} [encryptionKey] A custom encryption key.
* @property {number} [generation] Generation to scope the file to.
* @property {string} [kmsKeyName] Cloud KMS Key used to encrypt this
* object, if the object is encrypted by such a key. Limited availability;
* usable only by enabled projects.
* @property {string} [userProject] The ID of the project which will be
* billed for all requests made from File object.
* @property {Crc32cGeneratorCallback} [callback] A function that generates a CRC32C Validator. Defaults to {@link CRC32C}
*/
/**
* Constructs a file object.
*
* @param {Bucket} bucket The Bucket instance this file is
* attached to.
* @param {string} name The name of the remote file.
* @param {FileOptions} [options] Configuration options.
* @example
* ```
* const {Storage} = require('@google-cloud/storage');
* const storage = new Storage();
* const myBucket = storage.bucket('my-bucket');
*
* const file = myBucket.file('my-file');
* ```
*/
constructor(bucket: Bucket, name: string, options?: FileOptions);
/**
* The object's Cloud Storage URI (`gs://`)
*
* @example
* ```ts
* 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;
* ```
*/
get cloudStorageURI(): URL;
/**
* A helper method for determining if a request should be retried based on preconditions.
* This should only be used for methods where the idempotency is determined by
* `ifGenerationMatch`
* @private
*
* A request should not be retried under the following conditions:
* - if precondition option `ifGenerationMatch` is not set OR
* - if `idempotencyStrategy` is set to `RetryNever`
*/
private shouldRetryBasedOnPreconditionAndIdempotencyStrat;
copy(destination: string | Bucket | File, options?: CopyOptions): Promise<CopyResponse>;
copy(destination: string | Bucket | File, callback: CopyCallback): void;
copy(destination: string | Bucket | File, options: CopyOptions, callback: CopyCallback): void;
/**
* @typedef {object} CreateReadStreamOptions Configuration options for File#createReadStream.
* @property {string} [userProject] The ID of the project which will be
* billed for the request.
* @property {string|boolean} [validation] Possible values: `"md5"`,
* `"crc32c"`, or `false`. By default, data integrity is validated with a
* CRC32c checksum. You may use MD5 if preferred, but that hash is not
* supported for composite objects. An error will be raised if MD5 is
* specified but is not available. You may also choose to skip validation
* completely, however this is **not recommended**.
* @property {number} [start] A byte offset to begin the file's download
* from. Default is 0. NOTE: Byte ranges are inclusive; that is,
* `options.start = 0` and `options.end = 999` represent the first 1000
* bytes in a file or object. NOTE: when specifying a byte range, data
* integrity is not available.
* @property {number} [end] A byte offset to stop reading the file at.
* NOTE: Byte ranges are inclusive; that is, `options.start = 0` and
* `options.end = 999` represent the first 1000 bytes in a file or object.
* NOTE: when specifying a byte range, data integrity is not available.
* @property {boolean} [decompress=true] Disable auto decompression of the
* received data. By default this option is set to `true`.
* Applicable in cases where the data was uploaded with
* `gzip: true` option. See {@link File#createWriteStream}.
*/
/**
* 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.
*
* @param {CreateReadStreamOptions} [options] Configuration options.
* @returns {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 = 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'));
* ```
*/
createReadStream(options?: CreateReadStreamOptions): Readable;
createResumableUpload(options?: CreateResumableUploadOptions): Promise<CreateResumableUploadResponse>;
createResumableUpload(options: CreateResumableUploadOptions, callback: CreateResumableUploadCallback): void;
createResumableUpload(callback: CreateResumableUploadCallback): void;
/**
* @typedef {object} CreateWriteStreamOptions Configuration options for File#createWriteStream().
* @property {string} [contentType] Alias for
* `options.metadata.contentType`. If set to `auto`, the file name is used
* to determine the contentType.
* @property {string|boolean} [gzip] If true, automatically gzip the file.
* If set to `auto`, the contentType is used to determine if the file
* should be gzipped. This will set `options.metadata.contentEncoding` to
* `gzip` if necessary.
* @property {object} [metadata] See the examples below or
* {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert#request_properties_JSON| Objects: insert request body}
* for more details.
* @property {number} [offset] The starting byte of the upload stream, for
* resuming an interrupted upload. Defaults to 0.
* @property {string} [predefinedAcl] Apply a predefined set of access
* controls to this object.
*
* Acceptable values are:
* - **`authenticatedRead`** - Object owner gets `OWNER` access, and
* `allAuthenticatedUsers` get `READER` access.
*
* - **`bucketOwnerFullControl`** - Object owner gets `OWNER` access, and
* project team owners get `OWNER` access.
*
* - **`bucketOwnerRead`** - Object owner gets `OWNER` access, and project
* team owners get `READER` access.
*
* - **`private`** - Object owner gets `OWNER` access.
*
* - **`projectPrivate`** - Object owner gets `OWNER` access, and project
* team members get access according to their roles.
*
* - **`publicRead`** - Object owner gets `OWNER` access, and `allUsers`
* get `READER` access.
* @property {boolean} [private] Make the uploaded file private. (Alias for
* `options.predefinedAcl = 'private'`)
* @property {boolean} [public] Make the uploaded file public. (Alias for
* `options.predefinedAcl = 'publicRead'`)
* @property {boolean} [resumable] Force a resumable upload. NOTE: When
* working with streams, the file format and size is unknown until it's
* completely consumed. Because of this, it's best for you to be explicit
* for what makes sense given your input.
* @property {number} [timeout=60000] Set the HTTP request timeout in
* milliseconds. This option is not available for resumable uploads.
* Default: `60000`
* @property {string} [uri] The URI for an already-created resumable
* upload. See {@link File#createResumableUpload}.
* @property {string} [userProject] The ID of the project which will be
* billed for the request.
* @property {string|boolean} [validation] Possible values: `"md5"`,
* `"crc32c"`, or `false`. By default, data integrity is validated with a
* CRC32c checksum. You may use MD5 if preferred, but that hash is not
* supported for composite objects. An error will be raised if MD5 is
* specified but is not available. You may also choose to skip validation
* completely, however this is **not recommended**. In addition to specifying
* validation type, providing `metadata.crc32c` or `metadata.md5Hash` will
* cause the server to perform validation in addition to client validation.
* NOTE: Validation is automatically skipped for objects that were
* uploaded using the `gzip` option and have already compressed content.
*/
/**
* 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`.
*
*
* <p class="notice">
* 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.
* </p>
*
* NOTE: Writable streams will emit the `finish` event when the file is fully
* uploaded.
*
* See {@link https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload| Upload Options (Simple or Resumable)}
* See {@link https://cloud.google.com/storage/docs/json_api/v1/objects/insert| Objects: insert API Documentation}
*
* @param {CreateWriteStreamOptions} [options] Configuration options.
* @returns {WritableStream}
*
* @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.
* });
* ```
*/
createWriteStream(options?: CreateWriteStreamOptions): Writable;
/**
* Delete the object.
*
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {object} callback.apiResponse - The full API response.
*/
delete(options?: DeleteOptions): Promise<[r.Response]>;
delete(options: DeleteOptions, callback: DeleteCallback): void;
delete(callback: DeleteCallback): void;
download(options?: DownloadOptions): Promise<DownloadResponse>;
download(options: DownloadOptions, callback: DownloadCallback): void;
download(callback: DownloadCallback): void;
/**
* The Storage API allows you to use a custom key for server-side encryption.
*
* See {@link https://cloud.google.com/storage/docs/encryption#customer-supplied| Customer-supplied Encryption Keys}
*
* @param {string|buffer} encryptionKey An AES-256 encryption key.
* @returns {File}
*
* @example
* ```
* 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 <caption>include:samples/encryption.js</caption>
* region_tag:storage_upload_encrypted_file
* Example of uploading an encrypted file:
*
* @example <caption>include:samples/encryption.js</caption>
* region_tag:storage_download_encrypted_file
* Example of downloading an encrypted file:
*/
setEncryptionKey(encryptionKey: string | Buffer): this;
getExpirationDate(): Promise<GetExpirationDateResponse>;
getExpirationDate(callback: GetExpirationDateCallback): void;
generateSignedPostPolicyV2(options: GenerateSignedPostPolicyV2Options): Promise<GenerateSignedPostPolicyV2Response>;
generateSignedPostPolicyV2(options: GenerateSignedPostPolicyV2Options, callback: GenerateSignedPostPolicyV2Callback): void;
generateSignedPostPolicyV2(callback: GenerateSignedPostPolicyV2Callback): void;
generateSignedPostPolicyV4(options: GenerateSignedPostPolicyV4Options): Promise<GenerateSignedPostPolicyV4Response>;
generateSignedPostPolicyV4(options: GenerateSignedPostPolicyV4Options, callback: GenerateSignedPostPolicyV4Callback): void;
generateSignedPostPolicyV4(callback: GenerateSignedPostPolicyV4Callback): void;
getSignedUrl(cfg: GetSignedUrlConfig): Promise<GetSignedUrlResponse>;
getSignedUrl(cfg: GetSignedUrlConfig, callback: GetSignedUrlCallback): void;
isPublic(): Promise<IsPublicResponse>;
isPublic(callback: IsPublicCallback): void;
makePrivate(options?: MakeFilePrivateOptions): Promise<MakeFilePrivateResponse>;
makePrivate(callback: MakeFilePrivateCallback): void;
makePrivate(options: MakeFilePrivateOptions, callback: MakeFilePrivateCallback): void;
makePublic(): Promise<MakeFilePublicResponse>;
makePublic(callback: MakeFilePublicCallback): void;
/**
* The public URL of this File
* Use {@link File#makePublic} to enable anonymous access via the returned URL.
*
* @returns {string}
*
* @example
* ```
* 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();
* ```
*/
publicUrl(): string;
move(destination: string | Bucket | File, options?: MoveOptions): Promise<MoveResponse>;
move(destination: string | Bucket | File, callback: MoveCallback): void;
move(destination: string | Bucket | File, options: MoveOptions, callback: MoveCallback): void;
rename(destinationFile: string | File, options?: RenameOptions): Promise<RenameResponse>;
rename(destinationFile: string | File, callback: RenameCallback): void;
rename(destinationFile: string | File, options: RenameOptions, callback: RenameCallback): void;
request(reqOpts: DecorateRequestOptions): Promise<[ResponseBody, Metadata]>;
request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void;
rotateEncryptionKey(options?: RotateEncryptionKeyOptions): Promise<RotateEncryptionKeyResponse>;
rotateEncryptionKey(callback: RotateEncryptionKeyCallback): void;
rotateEncryptionKey(options: RotateEncryptionKeyOptions, callback: RotateEncryptionKeyCallback): void;
save(data: string | Buffer, options?: SaveOptions): Promise<void>;
save(data: string | Buffer, callback: SaveCallback): void;
save(data: string | Buffer, options: SaveOptions, callback: SaveCallback): void;
setMetadata(metadata: Metadata, options?: SetMetadataOptions): Promise<SetMetadataResponse>;
setMetadata(metadata: Metadata, callback: MetadataCallback): void;
setMetadata(metadata: Metadata, options: SetMetadataOptions, callback: MetadataCallback): void;
setStorageClass(storageClass: string, options?: SetStorageClassOptions): Promise<SetStorageClassResponse>;
setStorageClass(storageClass: string, options: SetStorageClassOptions, callback: SetStorageClassCallback): void;
setStorageClass(storageClass: string, callback?: SetStorageClassCallback): void;
/**
* Set a user project to be billed for all requests made from this File
* object.
*
* @param {string} userProject The user project.
*
* @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');
* ```
*/
setUserProject(userProject: string): void;
/**
* This creates a resumable-upload upload stream.
*
* @param {Duplexify} stream - Duplexify stream of data to pipe to the file.
* @param {object=} options - Configuration object.
*
* @private
*/
startResumableUpload_(dup: Duplexify, options: CreateResumableUploadOptions): 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).
*
* @param {Duplexify} dup - Duplexify stream of data to pipe to the file.
* @param {object=} options - Configuration object.
*
* @private
*/
startSimpleUpload_(dup: Duplexify, options?: CreateWriteStreamOptions): void;
disableAutoRetryConditionallyIdempotent_(coreOpts: any, methodType: AvailableServiceObjectMethods, localPreconditionOptions?: PreconditionOptions): void;
private getBufferFromReadable;
}
/**
* Reference to the {@link File} class.
* @name module:@google-cloud/storage.File
* @see File
*/
export { File };
|