Reputation: 1344
I have created a small Electron application which needs a small local MongoDB (community version) database.
Now I need to configure the start
and stop
scripts inside my package.json
so that every time I issue npm start
NPM first starts my MongoDB and once started runs my Electron application.
Currently my scripts
section in my package.json
looks like this:
"scripts": {
"stop": "mongodb/bin/mongo admin --eval 'db.shutdownServer()'",
"prestart": "mongodb/bin/mongod --dbpath mongodb/data/db --fork --logpath logs/mongodb/mongolog.txt",
"start": "electron . --fork > logs/mylog/mylog.txt"
}
The start
and prestart
scripts run just like I intended, but it seems that the stop
script does not get executed once my Electron app closes or I press Ctrl+C.
How can I achieve that when I close my Electron application or use Ctrl+C that my MongoDB server also shutsdown?
Upvotes: 1
Views: 2711
Reputation: 3432
Just like the start
script in the package.json
, the stop
script will only be executed if you issue npm stop
in your command line.
With Electron, you can detect when the app is going to close using app.on()
in your main process script. There are two events which are relevant here: before-quit
, which will execute just before Electron will close all windows and will-quit
, which will be issued after Electron closed all browser windows. Both events will be fired when your app quits because all the windows got closed, and when Electron receives a SIGINT
(Ctrl+C).
Using one of these two events, you will then be able to run the command you were trying to run using NPM:
const { exec } = require ("child_process");
// ...all of your main process' code...
app.on ("before-quit", (event) => {
exec ("mongodb/bin/mongo admin --eval 'db.shutdownServer()'");
process.exit (); // really let the app exit now
});
Upvotes: 2