首页 > 解决方案 > Node JS在winows中提取zip文件不起作用

问题描述

我正在尝试在窗口终端中解压缩受密码保护的 zip 文件。但是我收到错误消息,因为 “错误:'zip' 不被识别为内部或外部命令、可运行程序或批处理文件。”

var spawn = require('child_process').spawn;
let filePath = "XXX/XX";
let password= "abc";
extractZipWithPassword(filePath, password)
function extractZipWithPassword(filePath, password) {
    console.log("Inside here:::::::::::::::::::", filePath);
        var dir = spawn('zip',['-P', password, '-j', '-', filePath], {shell:true});
        dir.stderr.on('data', (data) => {
            console.log('Error: '+data);
            return filePath;
           })
        dir.on('close', (code) => {
            console.log("On closing:::::::::::::::")
            return filePath;
        });
}

标签: node.jspowershellnode-modules

解决方案


zip不是 Powershell 内置构造。您需要使用Expand-Archivecmdlet。

Expand-Archive -LiteralPath C:\Archives\Draft.Zip -DestinationPath C:\Reference

但是,Expand-Archive不适用于受密码保护的档案。不过,在我的情况下,我已经使用 using7zip来提取这些(请注意,您必须首先确保您当前的工作目录是目标解压缩目录):

spawn('7z', ['x', filePath, '-p' + password], { shell: true, cwd: destinationUnpackPath })

上面有几点需要说明:

  • -pPASSWORD将 PASSWORD 替换为实际密码。因此,如果您的密码是“12345”,则传递的参数将是-p12345.
  • 请注意,我添加cwdspawn选项,以确保正确设置当前工作目录。7z x会将存档解压缩到cwd.
  • 上面的代码中没有定义destinationUnpackPath,但这应该设置为目标提取路径

推荐阅读