2017-08-24 49 views
-1

我試圖編寫代碼,它將返回服務器是否已在運行。但是,我的測試不起作用。setinterval運行時不會調用退出函數

我要上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

重複的:https://stackoverflow.com/a/20165643/3042383 – lancew

+0

@lancew不是真的 –

回答

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}))