For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentHow to Exit a Process in Node.js: process.exit() Method

How to Exit a Process in Node.js: process.exit() Method

Published
29th Feb, 2024
Views
view count loader
Read it in
10 Mins
In this article
    How to Exit a Process in Node.js: process.exit() Method

    Development is a crucial task, as you might not know what will happen when you run your code. There could be several reasons that a Node.js application terminates either automatically or sometimes you need to do it forcefully or manually. You need to handle various services for your application's efficient and proper working. But if you are using Node.js for creating an interactive service, especially with the external system; you must go through this article, If you are eager to learn more, then learn node js online.

    There could be several reasons that can cause your Node.js process exit situation. You can take preventive measures to avoid some of those situations, but some will throw potential errors that require your attention. One of that situations is running out of memory and letting your application crash. In that scenario, taking the exit Node.js program is necessary to cause more harm to your application. 

    This article is useful for beginners and experienced professionals containing information about exiting your Node.js program. If you are looking for a job or change in a job with Node.js as a skill, you must go for a full stack developer course with a certification. This article will cover the following different ways to exit in node js.

    • Exiting of Script Implicitly
    • Using process.exit()
    • Using process.kill()
    • Using process.on()
    • Using process.abort

    Exiting of Script Implicitly

    This is one of the basic procedures to let the script exit implicitly from its working. You can encounter this at the command line interface. To explain the process methods, we are using the VS Code studio and its terminal.

    For your script to exit implicitly, you need to wait for the script to finish its execution. The code will automatically exit the process once it reaches the end and there is nothing to process further. 

    For example, we create an “ExitImplicit.js” file with the following code. This code will exit the code implicitly. Open your VS Code studio -> open folder (where you are saving your project) -> create a new file (ExitImplicit.js) under that folder and copy the below code -> save the file. 

    console.log('Code running'); 
    process.on('exit', function(code) { 
    return console.log(`exiting the code implicitly ${code}`); 
    }); 

    To run the code, we will run the following command from the VS Code terminal and see how the code will exit implicitly.

    As per the output, the first line is displayed on the screen, and then the exit callback starts. It prints the last line of the code on the screen. In this case, the code has exited implicitly, without any manual effort.

    But, if you change the above code with the repeating setInterval function, it will block your Node.js from getting exit. See the code below.

    console.log('Code running');
    process.on('exit', function(code) {
       return console.log(`exiting the code implicitly ${code}`);
    });
    setInterval((function() {
       return console.log('code still running');
    }), 1000);
    
    

    After running the above code, you will see the following output.

    The output will continue to appear on the screen until you press ctrl+c to exit from the code execution from the terminal. The execution stops after we press ctrl+c, and you are now exiting from the process.

    Another way to exit from the execution is to close the terminal.

    Using process.exit()

    If your Node.js process is not terminated properly, you can use the exit() function to terminate it forcefully. You need to do this by manually canceling the process in the terminal. The process.exit() is one of the commonly used and quick ways to terminate the process, even if the asynchronous calls are still running.

    Below is the syntax for the Node.js exit process. 

    process.exit(code)

    This function will take one parameter: the different status codes (exit codes). The possible exit codes for the nodejs process exit.

    Exit codesDescription
    Exit Code 0It will let the Node.js know to terminate the process when no async operations are performing. Without mentioning, it will take the default value of 0.
    Exit Code 1It is useful in case of fatal exceptions not handled by the domain. It is an efficient method to terminate the process.
    Exit Code 2Bash uses it for misuse.
    Exit Code 3You can use this exit code for the development where internal code cannot be parsed properly.
    Exit Code 4It is also used in the case of development where the JavaScript code fails to return the function value.
    Exit Code 5It is useful for fatal errors, such as the V8 engine cannot recover.
    Exit code 6It is useful when an internal fatal exception handler function is set to a non-function and cannot be called.
    Exit code 7Useful when an error is thrown while handling an uncaught expectation.
    Exit Code 8Unused, in easier versions, it specifies the uncaught exceptions.
    Exit Code 9It is when an extra value is provided for a non-required parameter, or we do not provide the value for a required parameter.
    Exit Code 10The JavaScript code in bootstrapping of Node.js throws an error while calling the bootstrap.
    Exit Code 12When you chose the wrong port number within the process.
    Exit Code 13It is useful when await is outside the function in the top-level code, but the passed Promise was never resolved.
    >128Used for fatal signals such as SIGKILL or SIGHU.P

    The process object is a global variable and thus can be accessed from anywhere without importing anything using the “require” function.

    For example, we are running the same code as above but with the process.exit() function. 

    console.log('Code running'); 
    process.on('exit', function(code) { 
    return console.log(`exiting the code implicitly ${code}`); 
    }); 
    setTimeout((function() { 
    return process.exit(22); //node js exit code  
    }), 5000); 
    
    


    console.log('Code running'); 
    process.on('exit', function(code) { 
    return console.log(`exiting the code ${code}`); 
    }); 
    setTimeout((function() { 
    return process.exit(1); //process exited with code 1 nodejs 
    }), 5000); 

    You can also use the process.exitCode for terminating the Node.js process safely. It terminates the process naturally without the need for an additional workaround. 

    Using process.kill()

    Another suitable method to terminate the Node.js process is to use the process.kill() function. The process.kill is a built-in Node.js method that takes different parameters to work properly. Below is the syntax of the process.kill() method. 

    process.kill(pid[, signal]) 

    pid is the process id and the signal is a string representing the signal names, such as SIGTERM, SIGINT, and SIGHUP. If you do not mention any signal name, it will consider the SIGTERM by default. These signals will transfer a small numeric message from one program to another. 

    Different OS has defined different signals, but the following are the standards compatible with every OS. 

    NameNumberHandleableSignal Purpose
    SIGHUP1YesTo close the parent terminal.
    SIGINT2YesTo interrupt a terminal, à la Ctrl + C
    SIGQUIT3YesTo make the terminal quit, à la Ctrl + D
    SIGKILL9NoTo forceful kill the process
    SIGUSR110YesUser-defined signal 1
    SIGUSR212YesUser-defined signal 2
    SIGTERM12YesRepresents a smooth process termination
    SIGSTOP19No

    This way of terminating the process is useful in highly concurrent applications that are running several processes concurrently. If you want to handle signals within your Node.js code, you need to listen for more events on the process object. Consider the following example and save the following code under the Exit.js file.

    #!/usr/bin/env node 
    console.log(`Process ID: ${process.pid}`); 
    process.on('SIGHUP', () => console.log('Received: SIGHUP')); 
    process.on('SIGINT', () => console.log('Received: SIGINT')); 
    setTimeout(() => {}, 5 * 10 * 20); // keep process alive 

    Once you run the above code in your VS Code terminal using “node Exit.js”. You will see that after pressing the crtl+c will not terminate the code. But, it will display the SIGINT signal. Now, open another terminal window and run the following command using the PID mentioned in the above image.

    $ kill -s SIGHUP 12390 

    You can encounter that one program can send a signal to another. 

    After this, we can see that we have exited from the process in the previous terminal, as the process has been killed.

    Now, if we consider the program that we have been using since the beginning using the process.kill method. 

    console.log('Code running'); 
    process.on('exit', function(code) { 
     return console.log(`exiting the code ${code}`); 
    }); 
    setTimeout((function() { 
    return process.kill(process.pid); 
    }), 5000); 

    Using process.on()

    Process.on is another interesting way of terminating the Node.js process implicitly. It is the same case that we have discussed in exiting the script implicitly. There we have used the process.on() method. It will automatically terminate the process once it reaches the end of the code.

    Below is the detailed explanation of how process.on() method works. We have created a ExitImplicit.js file with the below code. 

    console.log('Code running'); 
    process.on('exit', function(code) { 
    return console.log(`exiting the code implicitly ${code}`); 
    }); 

    To run the code, we will run the following command from the VS Code terminal and see how the code will exit implicitly.

    As per the output, you can see the first line is displayed on the screen, and then the exit callback started, then it prints the last line of the code on the screen. In this case, the code has exited implicitly, without any manual effort. 

    But, if you change the above code with the repeating setInterval function, it will block your Node.js from getting exit. See the code below. 

    console.log('Code running'); 
    process.on('exit', function(code) { 
    return console.log(`exiting the code implicitly ${code}`); 
    }); 
    setInterval((function() { 
    return console.log('code still running'); 
    }), 1000); 

    After running the above code, you will see the following output.

    The output will continue to appear on the screen until you press ctrl+c to exit from the code execution from the terminal. After we press ctrl+c, the execution stops and you are now exiting from the process.

    Using process.abort

    The process.abort is the similar process like other methods to terminate the process successfully. But the significant difference between this method and others is that it will immediately terminate the node.js program and then create a core file. To explain the abort process, we will be using the same example as above.

    console.log('Code running'); 
    process.on('exit', function(code) { 
     return console.log(`exiting the code ${code}`); 
    }); 
    setTimeout((function() { 
    return process.abort(); 
    }), 5000); 

    The code will run in between and automatically will abort when the time runs out.

    Unlock the Power of Python: Boost Your Career with our Python Course. Learn the language that's revolutionizing industries and gain a competitive edge. Enroll now!

    Conclusion

    While developing any application, you need to exit from the application to solve some errors and unexpected situations. Node.js provides some methods that will let you terminate the process safely. Different methods work differently but results in exiting from the Node.js process. Some methods will automatically exit the code but some require additional work around to exit. In this article, we have explained some process-related methods that will exit the process. So, go through the examples for better understanding.

    Frequently Asked Questions (FAQs)

    1How can I end a process in Node.js?

    Ending a process in Node.js is easy. You can use any of the following methods to do that. 

    • Exiting of Script Implicitly
    • Using process.exit() - process.exit (code)
    • Using process.kill() - process.kill(pid[, signal]) 
    • Using process.on() - process.on() 
    • Using process.abort - process.abort() 
    2What is the role of process exit In Node.js?

    If your Node.js process is not terminated properly, then you can use the process.exit() function to forcefully terminate it. You need to do this manually by canceling the process in the terminal. The process.exit() is one of the commonly used and quick ways to terminate the process even if the asynchronous calls are still running.

    Below is the syntax for the process.exit() method. 

    process.exit (code)

    3How can I stop a node process in Windows?

    To kill all running node processes in the Windows cmd promt. 

    taskkill /im node.exe /F 

    The taskkil is built-in Windows command that will kill all tasks. The /F flag is optional but when used it will forcefully terminate the process or task.

    4What is the meaning of Node.js process?

    The process in Node.js is a global object that you can access from anywhere and any project without the need to import it using the “require” function. The process is one of those objects. This is a crucial object for Node.js as it helps the developers to get significant information about the program’s runtime.

    Profile

    Aashiya Mittal

    Author

    Aashiya has worked as a freelancer for multiple online platforms and clients across the globe. She has almost 4 years of experience in content creation and is known to deliver quality content. She is versed in SEO and relies heavily on her research capabilities.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon