节点程序总是在处理中的任务之前退出。on('SIGINT')可以完成

时间:2019-02-23 02:53:21

标签: node.js

我试图让我的Node程序在Ctrl+C上正常退出,但是任务永远不会在程序退出之前完成。

index.js:

require('dotenv').config()
const log = require('./middleware/log')
const error = require('./middleware/error')
const mongoose = require('mongoose')
const puppeteer = require('puppeteer')
const cleanup = require('./middleware/cleanup');

(async () => {

  // handle Ctrl+C
  process.on('SIGINT', () => {
    cleanup(browser) // this never finishes before the program ends
    process.exit(2)
  })

  // log program exit
  process.on('exit', (code) => {
    if (code === 2) {
      log('Program exited manually.')
    } else if (code === 1) {
      log('Program crashed.')
    } else {
      log('Program exited.')
    }
    cleanup(browser) // I've tried putting it here too, but it still doesn't finish before the program ends
    process.exit(code)
  })

  await mongoose.connect(
    'mongodb://' + process.env.MONGO_USER_DEV + ':' + process.env.MONGO_PW_DEV + '@' + process.env.MONGO_IP_DEV + ':' + process.env.MONGO_PORT_DEV + '/' + process.env.MONGO_DB_DEV,
    {
      useNewUrlParser: true
    }
  )

  const browser = await puppeteer.launch({ headless: true })
  page = await browser.newPage()

  // do stuff

  cleanup(browser)

})().catch(async (err) => {
  cleanup(browser)
  error(err)
})

cleanup.js:

const mongoose = require('mongoose')

module.exports = (browser) => {
  mongoose.disconnect()
    .then(res => {
      browser.close()
        .then(res => {
          return
        })
    })
}

1 个答案:

答案 0 :(得分:0)

正常情况下,文档指出您不应该在清理中执行异步任务...但是,您可以在这篇冗长的重复帖子中找到hack。 doing a cleanup action just before node.js exits。希望对您有帮助。