本文整理汇总了TypeScript中@google-cloud/storage.Storage类的典型用法代码示例。如果您正苦于以下问题:TypeScript Storage类的具体用法?TypeScript Storage怎么用?TypeScript Storage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Storage类的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: 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);
}
});
};
示例2: 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);
}
});
};
示例3: 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);
});
示例4: 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);
};
示例5: 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()
}
示例6: 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
}
}
示例7: 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})
}
})
})
示例8: 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
}
示例9: 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}`)
}
}