首页 > 解决方案 > 如何在没有额外库的情况下在 linux 和/或 windows 中解压缩 zip 文件?

问题描述

该命令应该在 linux 或 windows 环境中工作,并且不依赖于任何其他库。

标签: node.js

解决方案


值得庆幸的是,在 Unix/Linux 世界中,我们几乎可以依靠unzip存在。假设使用 Powershell v5 的“现代”Windows,有一个等效的Expand-Archive命令。

const os = require("os");
const util = require("util");
const exec = util.promisify(require("child_process").exec);

async function unzip(file, destination) {
    const expandCommand = os.platform() === "win32" ?
        `powershell -command "& {&'Expand-Archive' ${file} -DestinationPath ${destination}}"` :
        `unzip ${file} -d ${destination}`;

    const { stdout, stderr } = await exec(expandCommand);
    return stderr ? Promise.reject(stderr) : stdout;
}

唯一棘手的部分是如何通过 exec 调用 powershell。


推荐阅读