Node.js中.js格式文件用node-7z-forall解压加密7z报错解决
解决.js文件中使用
node-7z-forall模块的import语法错误问题 方法1:在package.json中声明模块类型
- 到项目根目录的
package.json文件里,添加"type": "module"字段,这样Node.js会把所有.js文件当作ES模块处理,就能正常用import语句了。- 修改后的package.json示例:
{ "name": "your-project-name", "version": "1.0.0", "type": "module", "dependencies": { "node-7z-forall": "^x.x.x" } }
- 修改后的package.json示例:
- 注意:如果项目里还有用
require的CommonJS代码,需要一并改成import写法,或者单独对这类文件做处理。
方法2:改用CommonJS的require语法
- 要是不想改package.json的配置,直接把
import换成Node.js默认支持的require写法就行,适配CommonJS规范。- 原ES模块写法(.mjs里的):
import SevenZip from 'node-7z-forall'; - 改成CommonJS写法:
const SevenZip = require('node-7z-forall');
- 原ES模块写法(.mjs里的):
- 改完直接运行.js文件,不需要额外配置。
批量解压带密码7z文件示例(CommonJS版)
给你写个批量处理的示例,直接套用就行:
const SevenZip = require('node-7z-forall'); const fs = require('fs').promises; const path = require('path'); async function extractAll7zFiles(dirPath, password) { try { const files = await fs.readdir(dirPath); const sevenZipFiles = files.filter(file => file.endsWith('.7z')); for (const file of sevenZipFiles) { const fullPath = path.join(dirPath, file); const extractPath = dirPath; // 解压到当前目录 await SevenZip.extractFull(fullPath, extractPath, { password: password, overwrite: 'all' // 可选值:all(覆盖)/ skip(跳过)/ rename(重命名) }); console.log(`已完成解压:${file}`); } } catch (err) { console.error('解压出错:', err); } } // 替换成你的目标目录和密码 extractAll7zFiles('./your-target-folder', 'your-7z-password');
内容的提问来源于stack exchange,提问作者WALL-E
相关产品推荐
相关产品推荐

