我试图编写将返回服务器是否已经运行的代码。但是,我的测试不起作用。
我想在process.exit
上编写一个文件,说服务器不再运行,并且在服务器启动时写入服务器正在运行的文件:
const { readdir, writeFile, writeFileSync, readFileSync } = require('fs')
const IS_RUNNING_LOCATION = `${__dirname}/running.txt`
if (readFileSync(IS_RUNNING_LOCATION).toString() === 'true')
return
process.on('exit', () => {
writeFileSync(IS_RUNNING_LOCATION, 'false', {}, (err) => {
if (!err) return console.log('written')
console.log(err)
})
})
writeFileSync(IS_RUNNING_LOCATION, 'true')
setInterval(()=> console.log('running'), 1000)
但是,使用此代码时,当我使用^ C退出时,不会运行退出代码。
任何人都可以告诉我为什么会这样或我如何解决它?
答案 0 :(得分:0)
在这里找到答案:doing a cleanup action just before node.js exits
这是我最终使用的代码:
const { writeFileSync, readFileSync } = require('fs')
const IS_RUNNING_LOCATION = `${__dirname}/.running`
if (readFileSync(IS_RUNNING_LOCATION).toString() === 'true')
process.exit(0)
writeFileSync(IS_RUNNING_LOCATION, 'true')
function exitHandler(options, err) {
writefilesync(is_running_location, 'false', {}, (err) => {
if (!err) return if (!err) return console.log('written')
console.log(err)
})
if (options.exit) process.exit();
}
process.on('exit', exitHandler.bind(null,{cleanup:true}))
process.on('SIGINT', exitHandler.bind(null, {exit:true}))
process.on('uncaughtException', exitHandler.bind(null, {exit:true}))