Programmatically stopping MongoDB - javascript

I am working on an application using Node.JS, Electron. This application will run its own instance of MongoDB. The start up of Mongo is working using the following code:
child = childProcess.exec(`mongod --dbpath ${appConfig.dbConfigPath}`);
However, when the user exits the program, I want to stop mongo. I have tried the following, all taken from MongoDB Documentation
child = childProcess.exec('mongod --shutdown');
and
child = childProcess.exec(`kill -2 ${child.pid}`);
yet neither of these are shutting down the process.
This application is being developed to run on the windows platform.
For clarity, here is my app configuration file. The init() function is executed from within my main.js. The shutdown() is executed in the windowMain.on('close').
calibration.js
'use strict';
const childProcess = require('child_process');
const fileUtils = require('./lib/utils/fileUtils');
const appConfig = require('./config/appConfig');
let child;
class Calibration {
constructor() {}
init() {
createAppConfigDir();
createAppDataDir();
startMongo();
}
shutdown() {
shutdownMongo();
}
}
function createAppConfigDir() {
fileUtils.createDirSync(appConfig.appConfigDir);
}
function createAppDataDir() {
fileUtils.createDirSync(appConfig.dbConfigPath);
}
function startMongo() {
child = childProcess.exec(`mongod --dbpath ${appConfig.dbConfigPath}`);
console.log(child.pid);
}
function shutdownMongo() {
console.log('inside shutdownMongo');
//This is where I want to shutdown Mongo
}
module.exports = new Calibration();
main.js
'use strict'
const { app, BrowserWindow, crashReporter, ipcMain: ipc } = require('electron');
const path = require('path');
const appCalibration = require('../calibration');
appCalibration.init();
const appConfig = require('../config/appConfig');
let mainWindow = null;
ipc.on('set-title', (event, title) => {
mainWindow.setTitle(title || appconfig.name);
})
ipc.on('quit', () => {
app.quit();
})
// Quit when all windows are closed.
app.on('window-all-closed', function() {
if (process.platform != 'darwin') {
app.quit();
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
// Create the browser window.
mainWindow = new BrowserWindow({ center: true });
mainWindow.maximize();
mainWindow.setMinimumSize(770, 400);
mainWindow.loadURL(path.join(`file://${__dirname}`, '../ui/index.html'));
mainWindow.on('close', () => {
console.log('Inside quit')
appCalibration.shutdown();
app.quit();
});
mainWindow.on('closed', function() {
mainWindow = null;
});
});
Any assistance is greatly appreciated.

You can use Ipc to send orders through your js files.
In your main.js where you defined your electron, you can put this:
ipcMain.on("shutDownDatabase", function (event, content) {
// shutdown operations.
});
Then in some part of your application code, you can put a function like this:
function sendShutdownOrder (content){
var ipcRenderer = require("electron").ipcRenderer;
// the content can be a parameter or whatever you want that should be required for the operation.
ipcRenderer.send("shutDownDatabase", content);
}
Also I think you can use the events of Electron to shut down your db, this listens to the events of your mainWindow created when you start electron
mainWindow.on('closed', function () {
// here you command to shutdowm your data base.
mainWindow = null;
});
For more information about IPC you can see here and information about the events of your window here.

With Paulo Galdo Sandoval's suggestion, I was able to get this to work. However, I needed to get the PID for mongod from Windows Task manager. To do that I added the following function to the application configuration js file
function getTaskList() {
let pgm = 'mongod';
exec('tasklist', function(err, stdout, stderr) {
var lines = stdout.toString().split('\n');
var results = new Array();
lines.forEach(function(line) {
var parts = line.split('=');
parts.forEach(function(items) {
if (items.toString().indexOf(pgm) > -1) {
taskList.push(items.toString().replace(/\s+/g, '|').split('|')[1])
}
});
});
});
}
I also declared an array variable to place the located PID in. Then I updated my shutdown function
function shutdownMongo() {
var pgm = 'mongod';
console.log('inside shutdownMongo');
taskList.forEach(function(item) {
console.log('Killing process ' + item);
process.kill(item);
});
}
With this I am now able to start and stop Mongo as my application starts up and closes.
Thanks all

Related

Electron - fs.readdir callback sometimes doesn't execute on reload

About 30% of the time my electron app does not execute the fs.readdir callback after I've reloaded the window that contains that script. When I open the application with electron ., the issue never occurs, it only ever occurs after I've reloaded the window.
I've tried adding a setTimeout of 5 seconds before executing fs.readdir, however this didn't change anything. Additionally, after the first time fs.readdir is run, all proceeding fs.readdir callbacks are never executed unless done immediately afterwards or if the window has never been reloaded before.
Anyone know a why this occurs and a solution?
mainWindow.js:
const fs = require('fs')
// read all files in "images" directory
function readDirectory(){
fs.readdir('images', (e, files) => {
// On error, show and return error
if(e) return console.error(e);
console.log(files)
});
}
readDirectory()
main.js:
const electron = require('electron')
const path = require('path')
const {app, BrowserWindow, Menu} = electron
process.env.NODE_ENV = 'development'
let mainWindow
let mainMenu
function createMainWindow(){
// Create mainWindow
mainWindow = new BrowserWindow({
icon:'icon.png',
webPreferences:{
nodeIntegration:true,
fullscreen: true
}
})
// Load html file
mainWindow.loadFile('mainWindow.html')
// Main menu
mainMenu = Menu.buildFromTemplate(mainMenuTemplate)
// Set main menu
Menu.setApplicationMenu(mainMenu)
// Garbage handling
mainWindow.on('close',()=>{
mainWindow = null
mainMenu = null // idk if necessary
})
if (process.env.NODE_ENV !== 'production'){
mainWindow.webContents.openDevTools()
}
}
app.on('ready',e=>{
createMainWindow()
})
const mainMenuTemplate = [
{
role:'reload',
accelerator:'cmdorctrl+r',
}
]
Also, sometimes the content is read but then it seems like it disappears. Vid: https://imgur.com/a/qZjwSBi
If you're using the fs module set:
app.allowRendererProcessReuse = false;
https://github.com/electron/electron/issues/22119

Electron app.makeSingleInstance to avoid multiple instances thrown javascript error

I'm using electron 2.0.7 and I want to prevent multiple instances of the app by using app.makeSingleInstance.
It works but when i'm trying to run another instance of the app I get this error: "A Javascript error is occurred in the main process" as a pop up.
This is the code in main.ts:
function checkSingleInstance() {
// to make singleton instance
const isSecondInstance = app.makeSingleInstance((commandLine, workingDirectory) => {
// Someone tried to run a second instance, we should focus our window.
if (win) {
if (win.isMinimized()) {
win.restore();
win.focus();
}
}
});
if (isSecondInstance) {
app.quit();
return;
}
}
checkSingleInstance();
This is the error:
Try replacing app.quit() with app.exit().
app.exit() does not emit events before quitting as opposed to app.quit() which does the proper cleanup.
It's hard to say exactly where the error is coming from and why, but this issue is documented here.
After completing the source code you posted, I can run it using Electron 2.0.7 just fine.
The error you're seeing probably stems from some other part of your code. Judging by the error message, check if you import a module by the name screen somewhere.
Here's your source code, completed to a MCVE:
const {app, BrowserWindow} = require('electron')
let win = null
console.log(`Node ${process.versions.node}, Chrome ${process.versions.chrome}, Electron ${process.versions.electron}`)
function checkSingleInstance() {
// to make singleton instance
const isSecondInstance = app.makeSingleInstance((commandLine, workingDirectory) => {
// Someone tried to run a second instance, we should focus our window.
if (win) {
if (win.isMinimized()) {
win.restore();
win.focus();
}
}
});
if (isSecondInstance) {
console.log("Exiting because another instance is running")
app.quit();
return;
}
}
checkSingleInstance();
app.on('ready', () => {
win = new BrowserWindow({width: 200, height: 200});
win.on('closed', () => win = null);
});

WinAppDriver canonot find element when new window of desktop application created

"use strict";
require("./helpers/setup");
var wd = require("wd"),
_ = require('underscore'),
serverConfigs = require('./helpers/appium-servers'),
Q = require('q');
describe("Windows test from Node", function () {
this.timeout(300000);
var driver;
var allPassed = true;
before(function () {
var serverConfig = serverConfigs.local;
driver = wd.promiseChainRemote(serverConfig);
require("./helpers/logging").configure(driver);
var desired = _.clone(require("./helpers/caps").CMS);
return driver
.init(desired);
});
after(function () {
return driver
.quit();
});
afterEach(function () {
allPassed = allPassed && this.currentTest.state === 'passed';
});
it("should open CMS.", function () {
return driver
.elementByName('CharwellDB').doubleclick()
.sleep(20000);
});
it("should login CMS.", function () {
return driver
.elementByAccessibilityId('m_tbUserID').sendKeys("")
.elementByAccessibilityId('m_tbPassword').sendKeys("")
.elementByAccessibilityId('m_btnOk').click();
});
});
Hi, I'm using https://github.com/Clemensreijnen/AppiumOnWindowsWithJS/blob/master/README.md
framework and trying to automate a desktop application. After "should open CMS", a new desktop window open and the winappdriver couldn't locate the element on that window, I tried to work with WindowHandle but not going well with JavaScript, Please give some advise, thanks in advance!
I couldn't find my source code, but the solution is to implement windowHandle and as well as promise in JavaScript.

Bypassing proxy in Electron.js

Im having issues in bypassing proxy. I’m new to both JavaScript and Electron.
I'm either facing this issue (pic below) or a blank white screen will be loaded.
My pacfile.pac :
function findProxyForURL(url, host) {
// If the hostname matches, send direct.
if (dnsDomainIs(host, “http://000.00.0.0:0000”) ||
shExpMatch(host, “(*.domain.com)”))
return “DIRECT”;
}
my index.js:
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
const path = require('path')
const url = require('url')
var fs = require('fs');
var pac = require('pac-resolver');
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
let ProxyFunc
let pacVariable
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
//proxy: "http://000.00.0.0:0000"
// /* src="https://domain.name.com/#/random/login" */
/*mainWindow.webContents.session.setProxy({proxyRules:"http://000.00.0.0:0000"}, function () {
mainWindow.loadURL('https://domain.name.com/#/random/login');
});*/
app.commandLine.appendSwitch('proxy-bypass-list', '*.google.com;*domain.name.com;');
pacVariable = new pacfile();
pacVariable.findProxyForURL("https://domain.name.com/#/random/login", "*domain.name.com");
//ProxyFunc = new FindProxyForURL("https://domain.name.com/#/random/login","domain.name.com");
mainWindow.webContents.session.setProxy({proxyRules:"http://000.00.0.0:0000",proxyBypassRules:"domain.name.com"}, function () {
mainWindow.loadURL(path.join('file://', __dirname, 'index.html'));
});
/*mainWindow.webContents.session.setProxy({proxyRules:"http://000.00.0.0:0000"}, function () {
mainWindow.loadURL('https://domain.name.com/#/random/login');
});*/
mainWindow.openDevTools({ mode: 'bottom' });
// Open the DevTools.
// mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
Replace pacVariable = new pacfile() with
var FindProxyForURL = pac(fs.readFileSync('pacfile.pac'));
FindProxyForURL('https://domain.name.com/#/random/login').then((res) => {
console.log(res);
});
refer the docs for API
FindProxyForURL is a promise, so you'll have to write the code that requires the response inside the .then.

Trouble getting globalShortcut to register commands to index.js using send function in node/electron javascript app

for some reason my code is compiling with no error, however, my message "Helloworld" is not displaying properly in the console. however my test message is being displayed when i press the bound key combinations. below is my set of code, index.js and main.js
This is written for node/electron.
My main.js file:
//main.js
//requirements
const electron = require('electron');
const app = require('electron').app;
const BrowserWindow = require('electron').BrowserWindow;
const remote = require('electron').remote;
const ipc = require('electron').ipcMain;
const globalShortcut = require('electron').globalShortcut;
var mainWindow = null;
//create app, instantiate window
app.on('ready', function() {
mainWindow = new BrowserWindow({
frame: false,
height: 700,
resizable: false,
width: 368
});
mainWindow.loadURL(`file://${__dirname}/app/index.html`);
//this is the icp bind
globalShortcut.register('ctrl+shift+1', function(){
console.log("test")
mainWindow.webContents.send("testBindicp" ,"HelloWorld");
});
//this is the remote bind
globalShortcut.register('ctrl+shift+2', function(){
console.log("test")
mainWindow.webContents.send("testBindicp" ,"HelloWorld");
});
});
//close the app
ipc.on('close-main-window', function () {
app.quit();
});
below is my entire index.js:
//index.js
const globalShortcut = require('electron').globalShortcut;
const remote = require('electron').remote;
const ipc = require('electron').ipcRenderer;
//testing remote render from remote bind
remote.require('./main.js');
remote.on('testBindRemote', function(event){
console.log(event + " - test - from remote index.js");
});
//testing icpRenderer from icp bind
ipc.on('testBindicp', function (event) {
console.log(event + " - test - from icpRenderer on index.js")
});
//close the app
var closeEl = document.querySelector('.close');
closeEl.addEventListener('click', function() {
ipc.send('close-main-window');
});
the problem i'm having is when i press the keyboard binds, only the console logs from the main.js file are being send to the console. the close command is still working within the rendered window, but any other commands in the index.js window are not being bound to the proper main.js elements.
if i am doing something wrong, please let me know the proper way to implement these methodologies, as the remote and icp structures seem to be confusing to me.
Thank you.
You need to have another argument passed into the listening process ipc.on of index.js file, make it something like this:
ipc.on(<channel name>, function (event, arg) {
console.log(arg + " - test - from icpRenderer on index.js");
});
for more info, visit webContents API docs

Categories