Electron.js processes do not exit on app.quit - node.js

When I run app.quit() or app.exit(), the main app window gets closed, but 4 other electron processes keep running.
I thought it might be caused by a silent error, tried wrapping functions with try / catch, but nothing showed up.
I'd appreciate if someone helped me find the problem / explain what's wrong with the code
Code of the main Electron process:
https://github.com/aleksey-hoffman/sigma-file-manager/blob/main/src/electronMain.js
If you wanna run it, here's the instruction:
https://github.com/aleksey-hoffman/sigma-file-manager/blob/main/CONTRIBUTING.md

Found the problem - you have to remove some created window listeners such as closed, for Electron to quit properly.
Make sure you pass the same callback to removeListener
// Create window listeners
windows.quickViewWindow.once('closed', () => createQuickViewWindow)
// Remove window listeners
function removeWindowListeners () {
windows.quickViewWindow.removeListener('closed', () => createQuickViewWindow)
}
electron.app.on('before-quit', () => {
removeWindowListeners()
})

Related

Exit from express, nodejs programme on button click

I have created a file import functionality using nodejs,express and socket.io. Everything is working fine but now I have to implement a feature in which , user clicks on a button and on click of this button, I want to cancel/stop the execution of code (wherever the control is at that moment, should not execute further). I have tried return, res.end(), res.send(), eventEmitter, throw error etc but script processing is not getting stopped. On using process.exit, code execution stops but it shutdown for all users no matter from where they are operating(i.e if 5 users are using import feature, code executions stops for all five users). Can anybody have any other suggestions?
You can make an interval checking the if the state of the button (button click should change a flag) once you check the flag you can resolve your function ( the function should be a promise) and then it will stop the execution of the code example:
let flag = false
function test(){
return new Promise((res, rej)=>{
let interval = setInterval(()=>{
if (flag){
res();
}
},1000)
/*rest of code goes here*/
})
}

How to prevent(delay) OS(Windows 10) from closing Electron window?

I have made a desktop application using electron + node.js.
Sometimes Windows does automatic updates and restarts the OS.
I want to prevent Windows 10 from restarting until the data is saved (database is online so it takes some time to store data) in software.
Right now, I am using the below code to prevent the window from closing. After data save I am calling ipcMain.on('',function()) method and make lockwindow to true then i am calling window close method.
It is working when normally window close or use shortcut keys for a close window.
But this event is not emitted in case of force close or studown/restart
mainWindow.on('close', event => {
if (lockWindow) {
mainWindow.webContents.send('save', '');
mainWindow.webContents.once('dom-ready', () => {
mainWindow.webContents.send('save', '');
});
event.preventDefault();
createdialogWindow();
} else
mainWindow = null
})
Thank You.
Have a look at window events, specifically close and beforeunload.
You will have only limited time before the system restarts itself anyway.
If the OS or the user decides to kill your app, this is what is going to happen anyway (you can also upset / anger user for not playing nicely).
Lastly, would you like your application to be the reason why some crucial security updates did not install?
HTH

ws.onclose event does not get called on nodejs exit

i use web sockets and the onclose method does not get triggert when the server is down.
i tried to close the ws connections manually with progress.exit but it seems this only gets triggert on a clean exit.
is their a way to catch a stopped nodejs app and execute code before the stop?
it should trigger on ctr+c and any other crash/exit.
basicly i want to tell the client when the connection is not alive anymore before he is trying to do something, since onclose does not handel every case, what can i do to check the connection?
the only solution i came up with is to ping the server from time to time.
since this is not possible i started sending pings as a workarround:
var pingAnswer = true;
pingInterval = setInterval(function(){
if(pingAnswer){
ws.send(JSON.stringify({type:'ping'})); //on the serverside i just send a ping back everytime i recive one.
pingAnswer = false;
}else{
clearInterval(pingInterval);
//reload page or something
}
},1000);
ws.onMessage(function(e){
m = JSON.parse(e.data);
switch(m.type){
....
case 'ping':
pingAnswer=true;
return;
}
}
);
You don't provide a snippet showing how you're defining your on('close',...) handler, but it's possible that you're defining the handler incorrectly.
At the time of this writing, the documentation for websocket.onclose led me to first implement the handler as ws_connection.onclose( () => {...});, but I've found the proper way to be ws_connection.on('close', () => {...} );
Maybe the style used in the ws documentation is some kind of idiom I'm unfamiliar with.
I've tested this with node 6.2.1 and ws 1.1.1. The on.('close',...) callback is triggered on either side (server/client) when the corresponding side is shutdown via Ctrl+c or crashes for whatever reason (for example, for testing, JSON.parse("fail"); or throw new Error('');).

Node program with oriento does not exit after select

From within node.js I use the oriento module to access a OrientDB. In principle everything works fine, the only thing is the program dos not exit as it should. Here is the example:
const oriento = require("oriento");
const server = oriento({});
const db = server.use(dbname);
db.select("#rid").from("codelists").limit(1).scalar().then(function (result) {
console.dir(result);
}).finally(function () {
db.close();
server.close();
console.info("finished");
});
The programm executes the select, then the "then" and finally the "finally" clauses. All fine. But it does not exit. There seems to be something hanging on the event loop. But what? And how can I get rid of it? The problem actually is worse then just "press Ctrl-C" or have a process.exit() when everything is done, because the code is supposed to run within a unit test, where I cannot call exit. Any suggestions?
The problem is solved in the current master version of oriento. https://github.com/codemix/oriento/issues/170
You can use process._getActiveRequests() and process._getActiveHandles() to see what's holding the app open. They are undocumented but commonly used in this scenario.

Node.js: Will node always wait for setTimeout() to complete before exiting?

Consider:
node -e "setTimeout(function() {console.log('abc'); }, 2000);"
This will actually wait for the timeout to fire before the program exits.
I am basically wondering if this means that node is intended to wait for all timeouts to complete before quitting.
Here is my situation. My client has a node.js server he's gonna run from Windows with a Shortcut icon. If the node app encounters an exceptional condition, it will typically instantly exit, not leaving enough time to see in the console what the error was, and this is bad.
My approach is to wrap the entire program with a try catch, so now it looks like this: try { (function () { ... })(); } catch (e) { console.log("EXCEPTION CAUGHT:", e); }, but of course this will also cause the program to immediately exit.
So at this point I want to leave about 10 seconds for the user to take a peek or screenshot of the exception before it quits.
I figure I should just use blocking sleep() through the npm module, but I discovered in testing that setting a timeout also seems to work. (i.e. why bother with a module if something builtin works?) I guess the significance of this isn't big, but I'm just curious about whether it is specified somewhere that node will actually wait for all timeouts to complete before quitting, so that I can feel safe doing this.
In general, node will wait for all timeouts to fire before quitting normally. Calling process.exit() will exit before the timeouts.
The details are part of libuv, but the documentation makes a vague comment about it:
http://nodejs.org/api/all.html#all_ref
you can call ref() to explicitly request the timer hold the program open
Putting all of the facts together, setTimeout by default is designed to hold the event loop open (so if that's the only thing pending, the program will wait). You can programmatically disable or re-enable the behavior.
Late answer, but a definite yes - Nodejs will wait around for setTimeout to finish - see this documentation. Coincidentally, there is also a way to not wait around for setTimeout, and that is by calling unref on the object returned from setTimeout or setInterval.
To summarize: if you want Nodejs to wait until the timeout has been called, there's nothing you need to do. If you want Nodejs to not wait for a particular timeout, call unref on it.
If node didn't wait for all setTimeout or setInterval calls to complete, you wouldn't be able to use them in simple scripts.
Once you tell node to listen for an event, as with the setTimeout or some async I/O call, the event loop will loop until it is told to exit.
Rather than wrap everything in a try/catch you can bind an event listener to process just as the example in the docs:
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
});
setTimeout(function() {
console.log('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');
In the uncaughtException event, you can then add a setTimeout to exit after 10 seconds:
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
setTimeout(function(){ process.exit(1); }, 10000);
});
If this exception is something you can recover from, you may want to look at domains: http://nodejs.org/api/domain.html
edit:
There may actually be another issue at hand: your client application doesn't do enough (or any?) logging. You can use log4js-node to write to a temp file or some application-specific location.
Easy way Solution:
Make a batch (.bat) file that starts nodejs
make a shortcut out of it
Why this is best. This way you client would run nodejs in command line. And even if nodejs program returns nothing would happen to command line.
Making bat file:
Make a text file
put START cmd.exe /k "node abc.js"
Save it
Rename It to abc.bat
make a shortcut or whatever.
Opening it will Open CommandLine and run nodejs file.
using settimeout for this is a bad idea.
The odd ones out are when you call process.exit() or there's an uncaught exception, as pointed out by Jim Schubert. Other than that, node will wait for the timeout to complete.
Node does remember timers, but only if it can keep track of them. At least that is my experience.
If you use setTimeout in an arrow / anonymous function I would recommend to keep track of your timers in an array, like:
=> {
timers.push(setTimeout(doThisLater, 2000));
}
and make sure let timers = []; isn't set in a method that will vanish, so i.e. globally.

Resources