如何使用 NodeJS 即时解压缩托管的 tar 文件

How do I decompress a hosted tar file on the fly using NodeJS

我有以下运行良好的 curl 命令...

curl -L -v "https://us-central1-npm.pkg.dev/my-project/npm-public/@my-scope/bucky-barnes/-/@my-scope/bucky-barnes-0.0.1.tgz" -o test.tgz

这会输出一个我可以解压的 test.tgz 文件。

我正在尝试使用 NodeJS 自动执行此操作(请注意 -L 用于重定向)。我想出了以下...

import express from "express";
import tar from "tar-stream";
import https from "https";
const app = express();
const PORT = 3000;

const request = function(req, res, url) {
  const reqSent = https.get(url, (response) => {
    if (response.statusCode == 302 || response.statusCode == 307) {
      const url = `https://${reqSent.host}${response.headers.location}`;
      console.log("Redirecting ", url);
      request(req, res, url);
    } else {
      console.log("Extracting ", reqSent.host);
      const extract = tar.extract()
      extract.on('entry', function(header, stream, next) {
        console.log(`The filename is ${header.name}`)
        stream.on('end', function() {
          next() // ready for next entry
        })
        stream.resume() // just auto drain the stream
      })
      extract.on("error", (e)=>{
        res.status(500).send(`Error decompressing ${e}`)
      })
      extract.on('finish', function() {
        res.send("Completed")
      })
      response.pipe(extract);
    };
  } ).on("error", (e)=>{
    console.log(`There was an error ${e}`);
    res.status(500).send("Failed");
  });
};

app.use((req, res)=>{
  request(req, res, "https://us-central1-npm.pkg.dev/my-project/npm-public/@my-scope/bucky-barnes/-/@my-scope/bucky-barnes-0.0.1.tgz")
});
app.listen(PORT, () => console.log(`Server listening on port: ${PORT}`));

当我 运行 它失败时说 tar-streamer 无法解析响应...

Error decompressing Error: Unexpected end of data

我错过了什么?为什么管道不适用于 tgz 文件?

tgz 不是 tar。这是一个 gzipped tar-ball.

来自https://www.npmjs.com/package/tar-stream

Note that you still need to gunzip your data if you have a .tar.gz. We recommend using gunzip-maybe in conjunction with this.