Spawn MongoDB with Electron JS
Electron JS is a framework to build and run desktop apps using Javascript. More info on it can be found here.
Using Electron JS apps with MongoDB is straightforward. Use the already running MongoDB server and a library like Mongoose to get going. However, there might be instances when you would want to start the MongoDB server when launching the desktop app.
To get started, ensure that you have your Electron app setup and running, and MongoDB installed on your local machine.
//Mongodb spawn process
const spawn = require(‘child_process’).spawn;
const pipe = spawn(‘mongod’, [‘ — dbpath=YourDBPath’, ‘ — port’, ‘27018’]);
pipe.stdout.on(‘data’, function (data) {
console.log(data.toString(‘utf8’));
});pipe.stderr.on(‘data’, (data) => {
console.log(data.toString(‘utf8’));
});pipe.on(‘close’, (code) => {
console.log(‘Process exited with code: ‘+ code);
});
This will launch the MongoDB service and make the localhost URL available for the database. To ensure that the MongoDB service is stopped when quitting the desktop app, use the following code.
mainWindow.on(‘close’, (e) => {
console.log(‘application quit’)
pipe.kill(‘SIGINT’);
});
That’s all. Now you have a MongoDB service with a dedicated port that gets launched with the application.
Please leave your thoughts in the comments section. If you loved this article, use the claps to show your appreciation.