记录下Electron使用nsis批量打包的过程

396 阅读2分钟

安装NSIS

下载地址:nsis.sourceforge.io/Download

安装HW VNIS Edit

下载地址:sourceforge.net/projects/hm…

进入HM VNISEdit窗口

image.png

image.png

image.png

image.png

image.png

138925fb5fdc463be8079192d343c7f.png

image.png

image.png

image.png

image.png

image.png NSIS脚本创建完成之后,因为需要根据ID批量打很多个不同的安装包 所以用node编写一个自动打包的脚本 将nsis添加到系统环境变量,路径根据自己安装路径查找

image.png 在cmd中输入makensis输出下面的内容就没问题

image.png

// 获取json文件的数据,然后根据数据生成对应的exe文件
const data = require('./data.json');
// 引入exec方法操作cmd
const exec = require('child_process').exec;
// 引入fs模块操作文件
const fs = require('fs');
// 引入path模块操作路径
const path = require('path');
console.log(data.data);
// 获取json文件中的数据列表
const channelList = data.data;
// 定义一个方法,传入index,根据index获取对应的数据,然后生成对应的exe文件
function start(index) {
  return new Promise((resolve, reject) => {
    console.log(index);
    // 修改config.conf.json文件channelId 每个不同exe有不同的channelId 6是默认的
    const id = channelList[index].index_url ? Number(channelList[index].index_url) : 6;
    // 获取文件名
    const name = channelList[index].download_url.substring(channelList[index].download_url.lastIndexOf('/') + 1, channelList[index].download_url.lastIndexOf('.'));
    // 获取config.conf.json文件路径
    const configPath = path.join(__dirname, '../win-ia32-unpacked/resources/extraResources/config.conf.json');
    // 读取文件
    const currFile = fs.readFileSync(configPath);
    // 转换成对象
    const currFileObj = JSON.parse(currFile);
    // 修改channelId
    currFileObj.channelId = id;
    // 写入文件
    fs.writeFileSync(configPath, JSON.stringify(currFileObj), (err) => {
      if (err) {
        console.log(err);
      } else {
        console.log('写入成功');
      }
    });
    // 修改steamGoAutoInstall.nsi文件OutFile
    // 获取steamGoAutoInstall.nsi文件路径 这个就是使用hw生成的nsi脚本文件
    const nsiPath = path.join(__dirname, 'steamGoAutoInstall.nsi');
    // 读取文件
    const nsiFile = fs.readFileSync(nsiPath, 'utf-8');
    // 转换成字符串数组
    const nsiFileStr = nsiFile.toString();
    const nsiFileStrArr = nsiFileStr.split('\r\n');
    // 找到OutFile所在的行,然后修改OutFile
    const i = nsiFileStrArr.findIndex((item) => {
      return item.indexOf('OutFile') > -1;
    });
    // 修改OutFile,这里的路径是exe文件生成的路径以及文件名
    nsiFileStrArr[i] = `OutFile "allFiles\\${name}.exe"`;
    console.log(nsiFileStrArr[i]);
    // 写入文件
    fs.writeFileSync(nsiPath, nsiFileStrArr.join('\r\n'), (err) => {
      if (err) {
        console.log(err);
      } else {
        console.log('写入成功');
      }
    });
    // 执行cmd命令,生成exe文件
    const cmd = 'makensis steamGoAutoInstall.nsi'
    exec(cmd, (err, stdout, stderr) => {
      if (err) {
        console.log(err);
        reject(err);
      } else {
        console.log(stdout, `${name}_${id}.exe打包成功`);
        resolve();
      }
    });
  });
}

async function startAll() {
  // 循环执行start方法,生成所有的exe文件
  for (let index = 0; index < channelList.length; index++) {
    await start(index);
  }
}

startAll()

执行这个脚本文件就ok了!