0

When developing an API using nodeJS and express, 2 js file involved as below

When I pm2 start main.js, doSth() in api.js works as I expected, however, when I pm2 stop main.js, cleanSth() not working, anyone can advise how can I achieved my expected result (cleanSth when I pm2 stop)?

api.js

const express = require('express')

doSth()

const routes = (app) => { ... ... }

process.on('beforeExit', cleanSth()})

module.exports = routes

main.js

const express = require('express') const app = express()

const a = require('./api.js') a(app)

ytsm
  • 21
  • 5

1 Answers1

0

As stated in docs https://nodejs.org/api/process.html#process_event_beforeexit

The 'beforeExit' event is not emitted for conditions causing explicit termination, such as calling process.exit() or uncaught exceptions.

So if you only do some synchronous work in cleanSth then use exit event instead of beforeExit

Or you may want to have a look at this answer https://stackoverflow.com/a/64028857/3284355

Molda
  • 5,619
  • 2
  • 23
  • 39
  • The problem is that 'pm2 stop main.js' / 'pm2 restart main.js' do not trigger the 'beforeExit' or 'exit' event – ytsm Nov 26 '20 at 01:35