如何让 Google Cloud Storage 解压缩 gzip 文件?

问题描述

我正在从 FTP 服务器检索 gzipped csv 文件并将其存储在 Google Cloud Storage 中。我需要另一个 GCP 服务 Dataprep 来读取此文件。 Dataprep 仅适用于 csv,无法即时解压缩。

那么,解压缩它的正确方法是什么?这是我的代码

import FTPClient from 'ftp'

const file = bucket.file(path)

var ftpServer = new FTPClient()
ftpServer.on('ready',() => {
  ftpServer.get('/file.gz',(err,stream) => {
    if (err) throw err
    stream.once('close',() => {
      ftpServer.end()
      resolve(true)
    })
    stream.pipe(
      file.createWriteStream({
        resumable: false,public: false,gzip: true
      })
    )
  })
})
ftpServer.connect({
  host: 'somehost.com',user: 'user',password: '******'
})

我见过this question。我不确定这是否是最佳解决方案。据我了解,该代码将读取文件,将其加载到我的服务器内存中,然后将其写回。这似乎是对内存和流量的巨大浪费。有没有更好的解压方法

解决方法

我认为您不需要存储解压缩的文件。您需要设置正确的内容类型和内容编码(它会使用选项 <div class="image-wrap"> <a href="{{p.image_url}}"></a> <img src="https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg?v=47faa659a05e"> </div> 自动设置为 gzip,类似这样

gzip: true

如果请求者未在标头中设置标头 stream.pipe( file.createWriteStream({ contentType: 'text/plain',resumable: false,public: false,gzip: true }) ) ,则文件以未压缩形式提供。这是described in the documentation

,

想通了。我使用zlib

import zlib from 'zlib'

...
const unzipper = zlib.createGunzip()
stream.pipe(unzipper).pipe(
  file.createWriteStream({
    resumable: false,gzip: true
  })
)
...