child_process.exec(command[, options][, callback])
const{exec}=require("child_process")
/**
* 移动文件
*/
// exec("mv ./1.txt ./a ",{
// cwd:__dirname
// },(error)=>{
// console.log(error)
// })
/**
* 删除文件
*/
// exec('rm ./a.txt')
/**
* 复制文件目录
*/
// exec('cp -r ./1 ./b',{
// cwd:__dirname
// },(error)=>{
// console.log(error)
// })
exec 守护
const {exec}=require("child_process")
let serverList=['server1','server2']
serverList.forEach(serverName=>{
server(`node ./${serverName}.js`)
})
function server(cmd){
const worker=exec(cmd,(error,stdout,stderr)=>{
if(error)return console.error(error)
})
worker.stdout.on('data',data=>{
console.log(data)
})
worker.on("exit",(code)=>{
if(code===1){
setTimeout(()=>{
server(cmd)
},3000)
}
})
}
spawn
const{spawn}=require("child_process");
/**
* 当前目录文件名
*/
// const showInfo=spawn('ls')
// showInfo.stdout.on("data",(data)=>{
// console.log(data.toString())
// })
// showInfo.stderr.on("data",(data)=>{
// console.log(`stderr:${data}`)
// })
// showInfo.on("close",(code)=>{
// console.log(`子进程退出,退出码${code}`)
// })
spawn 守护
const {spawn}=require("child_process");
let serverList=['server1','server2']
serverList.forEach((serverName=>{
server(`./${serverName}.js`)
}))
function server(cmd){
const worker=spawn('node',[cmd])
worker.stdout.on('data',data=>{
console.log(data.toString())
})
worker.stderr.on("data",data=>{
console.log(data.toString())
})
worker.on("exit",code=>{
if(code===1){
setTimeout(()=>{
server(cmd)
},3000)
}
})
}
child_process.execFile(file[, args][, options][, callback])
const {promisify}=require("util");
const {exec,execFile,spawn,fork}=require("child_process")
const _execFile=promisify(require("child_process").execFile)
// _execFile('node',['--vision']).then(res=>{
// console.log(res.stdout)
// }).catch(err=>{
// console.log(err)
// })
execFile 守护
const { execFile } = require("child_process")
let serverList = ['server1', 'server2']
serverList.forEach((serverName => {
server(`./${serverName}.js`)
}))
function server(cmd) {
const worker = execFile('node', [cmd],(error,stdout,stderr)=>{
if(error)return console.log(error)
})
worker.stdout.on('data', data => {
console.log(data)
})
worker.on("exit", (code) => {
console.log(code)
if (code === 1) {
setTimeout(() => {
server(cmd)
}, 3000)
}
})
}
child_process.fork(modulePath[, args][, options])
const {work}=require("child_process") //从主进程中分离出的一个独立的子进程
function server(cmd){
const worker=fork([cmd])
worker.on("data",data=>{
console.log(data。stdout.toString())
})
}
let serverList=['server1','server2']
serverList.forEach(serverName=>{
server(`./${serverName}.js`)
})
fork 守护
const {fork} =require("child_process")
let serverList=['server1','server2']
serverList.forEach(serverName=>{
server(`./${serverName}.js`)
})
function server(cmd){
const worker=fork([cmd])
worker.on("data",(data)=>{
console.log(data.stderr)
})
worker.on("exit",(code)=>{
if(code===1){
setTimeout(()=>{
server(cmd)
},3000)
}
})
}