當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript Storage.bucket方法代碼示例

本文整理匯總了TypeScript中@google-cloud/storage.Storage.bucket方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Storage.bucket方法的具體用法?TypeScript Storage.bucket怎麽用?TypeScript Storage.bucket使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在@google-cloud/storage.Storage的用法示例。


在下文中一共展示了Storage.bucket方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: deleteEmptyBucket

 async deleteEmptyBucket() {
   const files = await this.listFiles('')
   if (files.entries.length > 0) {
     /* istanbul ignore next */
     throw new Error('Tried deleting non-empty bucket')
   }
   await this.storage.bucket(this.bucket).delete()
 }
開發者ID:blockstack,項目名稱:blockstack-registrar,代碼行數:8,代碼來源:GcDriver.ts

示例2: Promise

 const result: any = await new Promise((resolve, reject) => {
   this.storage
     .bucket(this.bucket)
     .getFiles(opts, (err, files, nextQuery) => {
       if (err) {
         reject(err)
       } else {
         resolve({files, nextQuery})
       }
     })
 })
開發者ID:blockstack,項目名稱:blockstack-registrar,代碼行數:11,代碼來源:GcDriver.ts

示例3: performWrite

  async performWrite(args: PerformWriteArgs): Promise<string> {
    if (!GcDriver.isPathValid(args.path)) {
      throw new BadPathError('Invalid Path')
    }
    if (args.contentType && args.contentType.length > 1024) {
      throw new InvalidInputError('Invalid content-type')
    }
    const filename = `${args.storageTopLevel}/${args.path}`
    const publicURL = `${this.getReadURLPrefix()}${filename}`

    const metadata: any = {}
    metadata.contentType = args.contentType
    if (this.cacheControl) {
      metadata.cacheControl = this.cacheControl
    }

    const fileDestination = this.storage
      .bucket(this.bucket)
      .file(filename)

    /* Note: Current latest version of google-cloud/storage@2.4.2 implements
       something that keeps a socket retry pool or something similar open for 
       several minutes in the event of a stream pipe failure. Only happens 
       when `resumable` is disabled. We enable `resumable` in unit tests so
       they complete on time, but want `resumable` disabled in production uses:
        > There is some overhead when using a resumable upload that can cause
        > noticeable performance degradation while uploading a series of small 
        > files. When uploading files less than 10MB, it is recommended that 
        > the resumable feature is disabled." 
       For details see https://github.com/googleapis/nodejs-storage/issues/312
    */

    const fileWriteStream = fileDestination.createWriteStream({
      public: true,
      resumable: this.resumable,
      metadata
    })

    try {
      await pipeline(args.stream, fileWriteStream)
      logger.debug(`storing ${filename} in bucket ${this.bucket}`)
    } catch (error) {
      logger.error(`failed to store ${filename} in bucket ${this.bucket}`)
      throw new Error('Google cloud storage failure: failed to store' +
        ` ${filename} in bucket ${this.bucket}: ${error}`)
    }

    return publicURL
  }
開發者ID:blockstack,項目名稱:blockstack-registrar,代碼行數:49,代碼來源:GcDriver.ts

示例4: createIfNeeded

 async createIfNeeded() {
   try {
     const bucket = this.storage.bucket(this.bucket)
     const [ exists ] = await bucket.exists()
     if (!exists) {
       try {
         await this.storage.createBucket(this.bucket)
         logger.info(`initialized google cloud storage bucket: ${this.bucket}`)
       } catch (err) {
         logger.error(`failed to initialize google cloud storage bucket: ${err}`)
         throw err
       }
     }
   } catch (err) {
     logger.error(`failed to connect to google cloud storage bucket: ${err}`)
     throw err
   }
 }
開發者ID:blockstack,項目名稱:blockstack-registrar,代碼行數:18,代碼來源:GcDriver.ts

示例5: Storage

export const importStorage = (projectId: string, foldername: string) => {
  const storage = new Storage({ projectId });
  const bucket = storage.bucket(`gs://${projectId}.appspot.com`);
  // TODO: progress
  const files = readdirSync(foldername);
  files
    .filter(file => !file.endsWith('.metadata'))
    .forEach(async file => {
      try {
        const { shouldResize, ...metadata } = JSON.parse(
          readFileSync(path.join(foldername, file + '.metadata'), 'utf8')
        );
        await bucket.upload(path.join(foldername, file), {
          metadata: { metadata },
        });
      } catch (error) {
        console.log(error);
      }
    });
};
開發者ID:accosine,項目名稱:poltergeist,代碼行數:20,代碼來源:restore.ts

示例6: async

export const exportStorage = async (projectId: string, foldername: string) => {
  const storage = new Storage({ projectId });

  const bucket = storage.bucket(`gs://${projectId}.appspot.com`);
  const [files] = await bucket.getFiles();
  ensureDirSync(foldername);
  files.forEach(async file => {
    try {
      await bucket.file(file.name).download({
        destination: path.join(foldername, `${file.name}`),
      });
      writeFileSync(
        path.join(foldername, `${file.name}.metadata`),
        JSON.stringify(file.metadata.metadata || {}, null, 2)
      );
    } catch (error) {
      console.log(error);
    }
  });
};
開發者ID:accosine,項目名稱:poltergeist,代碼行數:20,代碼來源:backup.ts

示例7: performDelete

  async performDelete(args: PerformDeleteArgs): Promise<void> {
    if (!GcDriver.isPathValid(args.path)) {
      throw new BadPathError('Invalid Path')
    }
    const filename = `${args.storageTopLevel}/${args.path}`
    const bucketFile = this.storage
      .bucket(this.bucket)
      .file(filename)

    try {
      await bucketFile.delete()
    } catch (error) {
      if (error.code === 404) {
        throw new DoesNotExist('File does not exist')
      }
      /* istanbul ignore next */
      logger.error(`failed to delete ${filename} in bucket ${this.bucket}`)
      /* istanbul ignore next */
      throw new Error('Google cloud storage failure: failed to delete' +
        ` ${filename} in bucket ${this.bucket}: ${error}`)
    }
  }
開發者ID:blockstack,項目名稱:blockstack-registrar,代碼行數:22,代碼來源:GcDriver.ts

示例8: Storage

  .storage.object().onFinalize(async object => {

    const gcs = new Storage();
    const bucket = gcs.bucket(object.bucket);
    const filePath = object.name;
    const contentType = object.contentType;
    const bucketDir = dirname(filePath);

    if (!contentType.startsWith('image/')) {
      console.log('This is not an image');
      return null;
    }

    const fileName = basename(filePath);
    if (fileName.startsWith('thumb_')) {
      console.log('Already a Thumbnail.');
      return null;
    }

    const workingDir = join(os.tmpdir(), 'thumbs');
    const tmpFilePath = join(workingDir, fileName);

    const metadata = {
      contentType: contentType,
    };

    await fs.ensureDir(workingDir);

    await bucket.file(filePath).download({
      destination: tmpFilePath
    });

    const uploadPromises = THUMBNAILSIZES.map(async thumbDef => {

      const thumbFileName = `thumb_${fileName}_${thumbDef.name}.${contentType.substring(contentType.indexOf('/') + 1)}`;
      const thumbFilePath = join(workingDir, thumbFileName);

      const fileTransform = sharp(tmpFilePath);

      if (object.contentType === 'image/jpeg') {
        fileTransform.jpeg({ quality: thumbDef.quality });
      }
      if (object.contentType === 'image/png') {
        fileTransform.png({ quality: thumbDef.quality });
      }

      if (thumbDef.width && thumbDef.height) {
        console.log(thumbDef);
        fileTransform.resize({ width: thumbDef.width, height: thumbDef.height });
      } else if (!thumbDef.width && thumbDef.height) {
        fileTransform.resize({ height: thumbDef.height });
      } else {
        fileTransform.resize(thumbDef.width);
      }

      await fileTransform.toFile(thumbFilePath);

      return bucket.upload(thumbFilePath, {
        destination: join(bucketDir, thumbFileName),
        metadata: metadata
      });
    });

    await Promise.all(uploadPromises);
    return fs.remove(tmpFilePath);
  });
開發者ID:Meistercoach83,項目名稱:sfw,代碼行數:66,代碼來源:generate-thumbnails.ts

示例9: Storage

export const uploadFile = (projectId: string, foldername: string) => {
  const storage = new Storage({ projectId });
  const bucket = storage.bucket(`gs://${projectId}.appspot.com`);
  return bucket.upload(foldername);
};
開發者ID:accosine,項目名稱:poltergeist,代碼行數:5,代碼來源:upload.ts


注:本文中的@google-cloud/storage.Storage.bucket方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。