是的,使用 spawn 并查找字符串,然后运行您的测试,监控 SIGTERM 和 SIGINT,然后将其传递给孩子。
const {
spawn
} = require('child_process')
// your cmd to start the server, possibly spawn('python', ['manage.py', 'startserver'])
const server = spawn('node', ['server.js'])
let timer = null
server.stdout.on('data', (data) => {
console.log(`stdout: ${data}`)
// look for the string in stdout
if (data.includes('Starting development server')) {
console.log('Commencing tests in 2 seconds')
timer = setTimeout(() => {
console.log('Run tests')
// ...
// tests complete
setTimeout(() => {
console.log('Tests completed, shutting down server')
server.kill('SIGINT')
}, 2000)
}, 2000)
}
})
server.stderr.on('data', (data) => {
clearTimeout(timer)
console.error(`stderr: ${data}`)
});
server.on('close', (code) => {
clearTimeout(timer)
console.log(`child process exited with code ${code}`);
});
process
.on('SIGTERM', shutdown('SIGTERM'))
.on('SIGINT', shutdown('SIGINT'))
.on('uncaughtException', shutdown('uncaughtException'))
function shutdown(signal) {
return (err) => {
console.log(`\n${signal} signal received.`)
if (err && err !== signal) console.error(err.stack || err)
console.log('Killing child process.')
server.kill(signal)
}
}
结果
node spawn.js
stdout: Starting development server http://localhost:8000
Commencing tests in 2 seconds
Run tests
Tests completed, shutting down server
stdout:
SIGINT signal received.
stdout: Closing HTTP server.
stdout: HTTP server closed.
child process exited with code 0
使用的测试服务器脚本如下,请注意上面它正在传回它收到的 SIGINT 信号。
const express = require('express')
const app = express()
const port = 8000
app.get('/', (req, res) => res.send('Hello World!'))
const server = app.listen(port, () => console.log(`Starting development server http://localhost:${port}`))
process
.on('SIGTERM', shutdown('SIGTERM'))
.on('SIGINT', shutdown('SIGINT'))
.on('uncaughtException', shutdown('uncaughtException'))
function shutdown(signal) {
return (err) => {
console.log(`\n${signal} signal received.`)
if (err && err !== signal) console.error(err.stack || err)
console.log('Closing HTTP server.')
server.close(() => {
console.log('HTTP server closed.')
//
process.exit(err && err !== signal ? 1 : 0)
})
}
}