如何在 NodeJS 中使用 tar 归档,同时只存储你想要的子目录?

How can you archive with tar in NodeJS while only storing the subdirectory you want?

基本上我想做与此 How to strip path while archiving with TAR 相同的事情,但是将 tar 命令导入到 NodeJS,所以目前我正在这样做:

const gzip = zlib.createGzip();
const pack = new tar.Pack(prefix="");
const source = Readable.from('public/images/');
const destination = fs.createWriteStream('public/archive.tar.gz');
pipeline(source, pack, gzip, destination, (err) => {
    if (err) {
        console.error('An error occurred:', err);
        process.exitCode = 1;
    }
});

但是这样做给我留下了像这样的文件:“/public/images/a.png”和“public/images/b.png”,而我想要的是像“/a.png”和“/b.png”。我想知道如何添加到此过程中以删除不需要的目录,同时将文件保留在原处。

您需要更改工作目录:

// cwd The current working directory for creating the archive. Defaults to process.cwd().
new tar.Pack({ cwd: "./public/images" });
const source = Readable.from('');

来源:documentation of node-tar

示例:https://github.com/npm/node-tar/blob/main/test/pack.js#L93