node执行批处理,并读取批处理生成的js文件(读取时清除缓存)
//jenkins部署时自动调run接口执行批处理,pm2起项目
const run = async (req, res) => {
const { branch } = req.body
console.log(branch)
spawn.sync('yarn -v', [], { stdio: 'inherit' })
spawn.sync(`run.bat ${branch}`, [], { stdio: 'inherit' })
spawn.sync(`runChild1.bat ${branch}`, [], { stdio: 'inherit' })
spawn.sync(`runChild2.bat ${branch}`, [], { stdio: 'inherit' })
delete require.cache[require.resolve('../../prettylist')]
const { prettylist } = require('../../prettylist')
spawn.sync(`runChild3.bat`, [], { stdio: 'inherit' })
prettylist.forEach(item => {
spawn.sync(`runChild4.bat ${item.pid}`, [], { stdio: 'inherit' })
})
spawn.sync(`runChild5.bat`, [], { stdio: 'inherit' })
delete require.cache[require.resolve('../../port')]
const { port } = require('../../port')
res.send({
state: 1,
data: {
prettylist,
port,
},
message: '成功'
})
}
run.bat:
@REM 接口/api/jenkins/run执行这个批处理
echo %0 %1
set historyPath=%cd%
echo %historyPath%
cd /temp/m-node-edu/%1
call yarn -v
call yarn
@REM name会自动应用到pm2配置文件ecosystem.config.js的name字段
set tempName=%1
set name=%tempName:\=_%
set watch=false
call pm2 start ecosystem.config.js --env production
@REM 跳转到原路径
cd %historyPath%
runChild1.bat:
@REM 接口/api/jenkins/run执行这个批处理 prettylist.txt保存pm2进程信息
pm2 prettylist > prettylist.txt
runChild2.bat:
@REM 接口/api/jenkins/run执行这个批处理 使用prettylist.txt以及其他文本生成prettylist.js,可以被js调用
echo const prettylist = > prettylist.js
type prettylist.txt >> prettylist.js
echo ; >> prettylist.js
echo module.exports = { prettylist } >> prettylist.js
echo prettylist.js done!
runChild3.bat:
@REM 接口/api/jenkins/run执行这个批处理 port.js保存pm2进程占用端口号的信息
echo const port = [ > port.js
runChild4.bat:
@REM 接口/api/jenkins/run执行这个批处理 port.js保存pm2进程占用端口号的信息
echo %0 %1
echo { pid: %1, info: ` >> port.js
netstat -ano | findstr %1 >> port.js
echo `}, >> port.js
runChild5.bat:
@REM 接口/api/jenkins/run执行这个批处理 port.js保存pm2进程占用端口号的信息
echo ]; >> port.js
echo module.exports = { port } >> port.js
echo port.js done!