Electron process object linked to function or global app? - node.js

I want to catch uncaught exceptions in an Electron app. I read that I could use
process.on("uncaughtException", err => {
console.log(err)
}
I am wondering if the process object is the general process of the app, or if it is the process of the function it was called in (if it can even be used that way)?
For example if I want to do process.exit or something similar, will it kill the app or shut down the function?
Thanks for your time !

From the docs:
The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require().
Yes the process object is the general process of the app.
So if you do process.exit it will quit the whole process.
Process docs

Related

setTimeout never calls when exception is thrown in different context

Using node.js, when I run the program
setTimeout(() => console.log("Timed out"), 0);
console.log("finishing");
I see
finishing
Timed out
But when I add a throw before "finishing"
setTimeout(() => console.log("Timed out"), 0);
throw new Error();
console.log("finishing");
I see
throw new Error();
^
Error
at Object.<anonymous> ...(stack trace here)...
And I don't see any mention of "Timed out".
Why is that? Even though the initial context would throw, once the stack was freed up, I expected the callback I passed to setTimeout would still run.
Does having an uncaught exception cause all timeouts to get canceled? Is this feature documented somewhere?
If I have multiple timeouts, is there a way for me to make sure that all the other timeouts continue to run when they can even if one of them happens to throw?
Unlike a web application running on browser, a Node application runs as a process on top of Google V8 JavaScript Engine. If you look into https://nodejs.org/api/timers.html is states that
The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers but use a different internal implementation that is built around the Node.js Event Loop.
As the above statement explains, even though the same global functions are available in both cases, their implementations are different. Therefore when an uncaught exception occurs in a Node application, all code related to timeouts will stop as the process is terminated. The best way to handle this is to properly handle all exceptions. You can use the below code to capture all uncaught exceptions from the process level itself.
process.on('uncaughtException', function(error) {
console.log(error);
});

Proper approach to code in node to catch SIGINT and other signals?

I'm a novice with node and javascript, and I'm more familiar with the old paradigm of synchronous programming rather than use of callbacks, promises, etc. in asynchronous programming offered in node and browser based javascript.
I was adding catching of SIGINT to some node scripts I was developing and noticed some peculiarity. I have a variety of node utility scripts. One is an express.js based app to serve stuff over HTTP. Another is a kafka message subscriber that processes messages coming to a specific topic on the bus. And a third one is a simple test/debug script for trying out node.
The express & kafka scripts handle SIGINT fine and terminate when the signal comes. But the simple debug script doesn't and continues operation even though I've sent Control + C (or D). So my question is, how should a novice write basic node code, when not using frameworks like express or a node kafka client that will already support this, to properly catch SIGINT? Here's my sample code below. Please suggest how to re-work (or encapsulate the relevant code for) it to catch the signal. As you can see, it's very basic code that a novice would likely write, like a hello world demo.
var sleep = require('sleep');
process.on('SIGINT', function() {
console.log("Performing graceful shutdown");
process.exit();
});
while(true){
console.log("running "+new Date());
sleep.sleep(1);
}
Node.js can't handle any event if the event loop is blocked.
The while(true){} in your codes will block the event loop, and all SIGINT will be queued in the event queue, it cannot be handled until the while breaks.
About event loop, please refer to this video.

NodeJS/SailsJS app database block

Understand that NodeJS is a single thread process, but if I have to run a long process database process, do I need to start a web worker to do that?
For example, in a sails JS app, I can call database to create record, but if the database call take times to finish, it will block other user from access the database.
Below are a sample code i tried
var test = function(cb) {
for(i=0;i<10000;i++) {
Company.create({companyName:'Walter Jr'+i}).exec(cb);
}
}
test(function(err,result){
});
console.log("return to client");
return res.view('cargo/view',{
model:result
});
On first request, I see the return almost instant. But if I request it again, I will need to wait for all the records being entered before It will return me the view again.
What is the common practice for this kinda of blocking issue?
Node.js has non-blocking, asynchronous IO.
read the article below it will help you to restructure your code
http://hueniverse.com/2011/06/29/the-style-of-non-blocking/
Also start using Promises to help you avoid writing blocking IO.

Express 4 / Node JS - Gracefully managing uncaughtException

I try my very best to ensure that there are no errors in my code, but occasionally there is an uncaught exception that comes along and kills my app.
I could do with it not killing the app, but instead output it to a file somewhere, and try to resume the app where it left off - or restart quietly and show a nice message to all users on the application that something has gone wrong and to give it a sec while it sorts itself out.
In the event of the app not running, it'd be good if it could redirect it to somewhere that says "The app isn't running, get in touch to let me know" or something like that.
I could use process.on('uncaughtException') ... - but is this the right thing to do?
Thank you very much for taking the time to read this, and I appreciate your help and thoughts on this matter.
You can't actually resume after a crash, not at least without code written specifically for that purpose, like defining state and everything.
Otherwise use clusters to restart the app.
// ... your code ...
var cluster = require('cluster');
process.on('uncaughtException', function(err){
//.. do with `err` as you please
cluster.fork(); // start another instance of the app
});
When it forks, how does it affect the users - do they experience any latency while it's switching?
Clusters are usually used to keep running more than a single copy of your node app at all times, so that while one of the workers respawns, others are still active and preventing any latency.
if (cluster.isMaster)
require('os').cpus().forEach(cluster.fork);
cluster.on('exit', cluster.fork);
Is there anything that I should look out for, e.g. say there was an error connecting to the database and I hadn't put in a handler to deal with that, so the app kept on crashing - would it just keep trying to fork and hog all the system resources?
I've actually not thought about that concern before now. Sounds like a good concern.
Usually the errors are user instigated so it's not expected to cause such an issue.
Maybe database not connecting issue, and other such unrecoverable errors should be handled before the code actually goes into creating the forks.
mongoose.connection.on('open', function() {
// create forks here
});
mongoose.connection.on('error', function() {
// don't start the app if database isn't working..
});
Or maybe such errors should be identified and forks shouldn't be created. But you'll probably have to know in advance which errors could those be, so you could handle them.

Synchronization in Firefox OS (B2G)

I would like to stop a function in order to wait the end of another section of code.
Is there in Firefox OS some synchronization method like wait() and notify() in Java?
Thanks
JavaScript doesn't has this concept, but generally speaking uses callbacks (function pointers). A bit like the anonymous classes in Java. For example, I'm making a call to a web server:
function callToWebServer(url, doneCallback) {
// do all kinds of magic, waiting for the web server to reply etc.
// when done:
doneCallback();
}
Now using it via:
callToWebServer(function() {
// this is executed after the call to the web server succeeded
});
alert(1); // this is executed straight away
We can never wait, as JS is a single-thread execution environment. All code is written async.

Resources