Limitation of Using process.exit() with Node.JS

in #nodejs7 years ago

With the recurrent changes in technology, more and more startups are opting new innovations. One of the famous cutting-edge examples is Node.js. It is a new wave of technology which allows executing JavaScript on the server side. This open-source platform is built to run fast and scalable server-side as well as networking applications. Apart from reliable runtime environment, one of the issues that recently came up in a coding review was the use of process.exit(). In Node.js script, a process is an object which can be retrieved from anywhere. It makes the script, stop immediately when there is no event handler waiting for an event.

Limitation of using process.exit()

• By calling process.exit() in an exit code, the whole processing comes to an end. Even, the exit event and event loop stops. Soon, the Node.js completely stops and returns the specified exit code. It means that process.exit() restricts the Node.JS from doing anything.

• The use of specified exit code is not a real problem as many programming languages offer this capability. The real difficulty is the process.exit() which can be called by any application at any time. This makes the entire application to shut down.

• Any segment of the exit code can call the process.exit() which means that the function which is called, is responsible for making the application completely stopped. This is not a good thing as there should be an area of application which decides when to call the process.exit().

A Solution to the Problem

When you think of using process.exit(), you must consider throwing an error. Throw an error delivers the same effect such as process.exit() in the code execution. Only by calling such functions you can catch the errors and respond to them in an appropriate manner. If there is no use of any event handlers, then the Node.js will fire the exit event and process.exit() is called. On the opposite side, if there are event handlers, then it’s your choice whether to call the process.exit() in order to use the exit code. However, throwing an error is the key which gives an opportunity to capture the errors in an application and recover from it.

For your entire application, if there is a need to call the process.exit(), then it should be in application controller. For a programmer, it’s better to use throw an error instead of process.exit(). It is an effective way which recovers the applications from errors. Dealing with error is common but the only way to defeat them is practicing on proper codes. To work on complex codes and sharpening your skill for interviews, visit CodeFights. This is a best platform for all your programming needs and practicing coding here makes you perfect in cracking technical interviews.