2030

What is the command that is used to exit? (i.e terminate the Node.js process)

700 Software
  • 77,509
  • 74
  • 213
  • 324

21 Answers21

2554

Call the global process object's exit method:

process.exit()

From the docs:

process.exit([exitcode])

Ends the process with the specified code. If omitted, exit uses the 'success' code 0.

To exit with a 'failure' code:

process.exit(1);

The shell that executed node should see the exit code as 1.

SP Tutors
  • 238
  • 2
  • 6
Pero P.
  • 22,259
  • 7
  • 56
  • 79
  • 6
    Just want to add something. If you are handling a request, you should also `end()` the request as well. Otherwise, it'll just hang. – pixelfreak Mar 03 '12 at 18:16
  • 134
    @pixelfreak, `exit` isn't misleading at all. You are confused about how Node works. Think of Node as the server itself. It isn't just fired up as needed, like PHP is within a web server like Apache. Node doesn't even have to have anything to do with web servers at all! It's just a host for some JavaScript, with some nifty built-in libraries for doing useful things. – Brad Sep 20 '12 at 14:22
  • 6
    @Brad And PHP is a general purpose language. No need to run it with `mod_php` or use Apache. You can reimplement an httpd in PHP like node does if you really want or use a more sane/standardized approach like FastCGI just like you can in node. – binki Aug 08 '16 at 01:30
  • 48
    Please note that `process.exit()` is **not recommended**, as described in [this answer below](https://stackoverflow.com/a/37592669/199263). – AndreasPizsa Dec 08 '17 at 13:52
  • Off-topic slightly, but I've seen people use `process.exit(-1)`. Why's that? – PiggyPlex Jan 22 '21 at 20:00
514

Just a note that using process.exit([number]) is not recommended practice.

Calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to process.stdout and process.stderr.

In most situations, it is not actually necessary to call process.exit() explicitly. The Node.js process will exit on its own if there is no additional work pending in the event loop. The process.exitCode property can be set to tell the process which exit code to use when the process exits gracefully.

For instance, the following example illustrates a misuse of the process.exit() method that could lead to data printed to stdout being truncated and lost:

// This is an example of what *not* to do:
if (someConditionNotMet()) {
  printUsageToStdout();
  process.exit(1);
}

The reason this is problematic is because writes to process.stdout in Node.js are sometimes asynchronous and may occur over multiple ticks of the Node.js event loop. Calling process.exit(), however, forces the process to exit before those additional writes to stdout can be performed.

Rather than calling process.exit() directly, the code should set the process.exitCode and allow the process to exit naturally by avoiding scheduling any additional work for the event loop:

// How to properly set the exit code while letting
// the process exit gracefully.
if (someConditionNotMet()) {
  printUsageToStdout();  
  process.exitCode = 1;
}
Sergey Brunov
  • 11,755
  • 7
  • 39
  • 71
Dominic
  • 48,717
  • 14
  • 109
  • 126
  • 40
    This is the best answer, by far. Other answers might not allow node to properly process pending events before exit, very sad :( – djabraham Oct 26 '16 at 05:13
  • 5
    Agreed, this should have more upvotes! I had a node script that was kicking off multiple child processes via shelljs.exec and I wanted my overall script to return with an error exit code if any of the child processes failed. process.exitCode = 1 worked great in the exec callbacks (whereas simply calling process.exit(1) in there would exit the main script before all child processes finished!) – Nick B Nov 23 '16 at 15:10
  • 16
    I used this answer and found that my process never actually exited. Had to ctrl-C it. – jcollum Jan 26 '17 at 16:32
  • 1
    Then I'd imagine something is keeping it open - if you do `echo "console.log('hello')" >> ./test.js && node test.js` you should see it print hello and then exit – Dominic Jan 26 '17 at 16:58
  • 2
    If you fork a child process you MUST `child.disconnect();` for `process.exitCode=0` (or `1`) to take affect. Not disconnecting will cause your program to hang. https://nodejs.org/dist/latest-v6.x/docs/api/process.html#process_process_disconnect – Cody G Aug 30 '17 at 20:57
  • 46
    There are many uses cases for immediate process and pending event termination. That is exactly what `process.exit()` is intended for. – Dominic Cerisano Jan 01 '18 at 21:43
  • 10
    This is not the best answer by any stretch because it doesn't answer the question. Instead, it gives best practices on how to develop code flow for a nodejs program. – anon58192932 Jan 08 '18 at 21:46
  • 3
    Hence why the answer is prefixed with "Just a note" – Dominic Feb 13 '18 at 09:19
  • Please be aware that referenced documentation is for version 9. This may not equally apply for previous versions of NodeJS. – Alberto Mendoza Mar 23 '18 at 15:55
  • Actually this quote is from Jun 2016 and the docs still haven't changed for v9 :) – Dominic Mar 23 '18 at 15:58
  • 1
    This showed me that my express server wasn't safely exiting and probably saved me from tracking down an annoying issue of truncated data due to forced termination of a mid-process thread. Definitely use this over the function and safely clean up your long-living objects. Took like 3 minutes to fix, who knows how long a truncated data issue would have taken for me to realize why it happened. – abelito Apr 21 '19 at 14:59
  • 1
    But if you are working with async/await and controlling your event loops, if you need to exit the app you should know at this point nothing else is waiting to be executed in the next tick. I agree it's not right to have this when you run an express for example, but if your run a script, you can totally do it properly by your hands. About the express, I'm sure there is a way to wait for a signal closing the socket and then you can fire up the exit – Vincent Jun 21 '19 at 08:56
  • 1
    This question probably comes up a lot with people not understand how async operations work. They start something, like listening on a socket, and then never close it. They leave DB connections open. And then the complaint is `it's not closing! so I need to force it`. Basically, if you are reading this, chances are you are doing something wrong. – user3427419 Aug 23 '19 at 17:14
  • I think this is the best answer out of all. – Aviv Lo May 06 '20 at 16:59
  • If you run `process.exit(1)` after an operation like console.log or console.error, is there a chance that the program will exit before the data is sent to the console? Does this only affect asynchronous processes? – Christopher Bradshaw Sep 18 '20 at 17:00
  • @Dominic I really appreciate this note. I think what would tie it to the question more and provide a better answer is add how a person would go about finding what is keeping node running. For example: https://stackoverflow.com/questions/26337780/how-can-i-find-out-why-nodejs-isnt-exiting-cleanly, https://github.com/mafintosh/why-is-node-running or process._getActiveHandles() – Marty Apr 22 '21 at 18:58
375

From the official nodejs.org documentation:

process.exit(code)

Ends the process with the specified code. If omitted, exit uses the 'success' code 0.

To exit with a 'failure' code:

process.exit(1);
MiniGod
  • 3,363
  • 1
  • 23
  • 26
alienhard
  • 13,366
  • 9
  • 34
  • 28
  • 1
    Could `process.exit(code=0)` be rewritten as `code = 0; process.exit(0)`? – Armand Feb 12 '13 at 08:44
  • 9
    @Alison yes, or more precisely `code = 0; process.exit(code);` – wprl Feb 21 '13 at 16:29
  • 7
    Is it true that if you're exiting, you probably don't care about the value of `code`? – Armand Feb 21 '13 at 17:26
  • You can always yourself determine, depending on that you don't override an already existing error code, where the program exited and with which error code. – Johan S Mar 23 '13 at 22:11
  • 1
    So funny, I tried with all exit, quit, end, stop but none of them worked, and the correct one is yours :D. Thanks. – Tien Do Aug 14 '13 at 04:17
  • 8
    @Alison A better idea is just `process.exit()` with no parameter as code defaults to 0 – Jeremy Moritz Mar 28 '14 at 18:01
  • 2
    @Armand You are correct -- Code is just a variable, and in this case used to indicate what the parameter is. So .exit(0) does everything the example does. – Gerard ONeill Jun 07 '14 at 19:15
  • 25
    @Armand the code is not for you, it's for whatever ran your code. For example, if you create an exit_0.js with `process.exit(0);` and run it with `node exit_0.js && echo 'success'` it will say "success". If you create exit_1.js with `process.exit(1);` and run `node exit_1.js && echo 'success'` it will not say "success" since your process exited with a non-zero (which indicates a "failure" or "abnormal exit" to the shell). In addition, you will see different values in `$?` if you run `node exit_1.js` vs `node exit_0.js` (you can check by doing `node exit_1.js` and then doing `echo $?`). – msouth Aug 22 '14 at 17:03
284

If you're in a Unix terminal or Windows command line and want to exit the Node REPL, either...

  • Press Ctrl + C twice, or
  • type .exit and press Enter, or
  • press Ctrl + D at the start of a line (Unix only)
Mark Amery
  • 110,735
  • 57
  • 354
  • 402
Mohsen
  • 58,878
  • 30
  • 149
  • 175
  • 15
    Note that, beyond Node, the Ctrl+D shortcut on Mac or Linux works on almost all shells and REPLs you'll ever encounter, including Unix shells like Bash, the shells for databases like MySQL and PostgreSQL, and the REPLs for programming languages like Python, PHP, and Ruby. It is the only method of exiting shells I ever use. – Mark Amery May 23 '15 at 22:52
  • 2
    For the `node` REPL, Ctrl+D to exit is a standard behavior, so it also works on Windows. – Alan Dec 31 '17 at 15:33
  • Press Ctrl + C (even on a Mac!) – Prince Oct 01 '19 at 13:54
125

From the command line, .exit is what you want:

$ node
> .exit
$

It's documented in the REPL docs. REPL (Read-Eval-Print-Loop) is what the Node command line is called.

From a normal program, use process.exit([code]).

Mike M. Lin
  • 9,732
  • 12
  • 51
  • 60
87

It depends on the reason why you're willing to exit node.js process, but in any case process.exit() is the last option to consider. A quote from documentation:

It is important to note that calling process.exit() will force the process to exit as quickly as possible even if there are still asynchronous operations pending that have not yet completed fully, including I/O operations to process.stdout and process.stderr.

In most situations, it is not actually necessary to call process.exit() explicitly. The Node.js process will exit on it's own if there is no additional work pending in the event loop. The process.exitCode property can be set to tell the process which exit code to use when the process exits gracefully.

Let’s cover possible reasons why you might be willing to exit node.js process and why you should avoid process.exit():

Case 1 - Execution complete (command line script)

If script has reached its end and node interpreter doesn't exit, it indicates that some async operations are still pending. It’s wrong to force process termination with process.exit() at this point. It’s better to try to understand what is holding your script from exiting in expected way. And when you settle this, you can use process.exitCode to return any result to calling process.

Case 2 - Termination because of external signal (SIGINT/SIGTERM/other)

For example, if you’re willing to gracefully shut down an express app. Unlike command line script, express app keeps running infinitely, waiting for new requests. process.exit() will be a bad option here because it’s going to interrupt all requests which are in pipeline. And some of them might be non-idempotent (UPDATE, DELETE). Client will never know if those requests are completed or not on server side and it might be the reason of data inconsistency between client and server. The only good solution is to tell http server to stop accepting new requests and wait for pending ones to finish with server.close():

var express = require('express');
var app = express();
var server = app.listen(80);

process.on( 'SIGTERM', function () {
   server.close(function () {
     console.log("Finished all requests");
   });
});

If it still doesn't exit - see Case 1.

Case 3 - Internal error

It's always better to throw an error, you’ll get a nicely formatted stack trace and error message. Upper levels of code can always decide if they can handle error (catch) or let it crash the process. On the other side, process.exit(1) will terminate process silently and there will be no chance to recover from this. It might be the only “benefit” of process.exit(), you can be sure that process will be terminated.

Community
  • 1
  • 1
teq
  • 1,196
  • 8
  • 10
  • 5
    Amazing response. `Process.exit()` looks like major overkill for most applications. I was looking for an equivalent to php's die() function... more like: `throw new Error('die msg')` – AvadData May 12 '17 at 12:39
  • If one has a bunch of code which is supposed to execute continuously until a shutdown request is received, is there any nice convention for registering events that would allow subscriptions to be abandoned in response to a shutdown request, without that requiring the code using the events or the code requesting the shutdown have specific knowledge about each other? Unfortunately, the only way I can think of to kinda-sorta implement that would be to require that any piece of code that registers an event also create a wrapper which includes a closure to unregister it. – supercat Mar 29 '18 at 16:50
  • This should be the accepted answer. It explains `process.exit()`, `process.exitCode`, signal handling and (what I want) `throw new Error` to exit. – dturvene Jun 26 '20 at 00:13
28

REPL(Command Line)

  • Press ctrl + c twice

  • Type .exit and press enter

Script File

process.exit(code)

Node normally exits with code 0 when no more async operations are pending.

process.exit(1) should be used to exit with a failure code.This will allow us to infer that node didn't close gracefully and was forced to close.

There are other exit codes like

3 - Internal JavaScript Parse Error ( very very rare)

5 - Fatal error in v8 javascript engine

9 - Invalid argument

For full list see node exit codes

Siva Prakash
  • 3,894
  • 31
  • 26
13

I have an application which I wanted to:

  1. Send an email to the user
  2. Exit with an error code

I had to hook process.exit(code) to an exit event handler, or else the mail will not be sent since calling process.exit(code) directly kills asynchronous events.

#!/usr/bin/nodejs
var mailer = require('nodemailer');
var transport = mailer.createTransport();
mail = {
  to: 'Dave Bowman',
  from: 'HAL 9000',
  subject: 'Sorry Dave',
  html: 'Im sorry, Dave. Im afraid I cant do <B>THAT</B>.'
}
transport.sendMail(mail);
//process.exit(1);
process.on('exit', function() { process.exit(1); });
Stephen Quan
  • 15,118
  • 3
  • 69
  • 63
  • 4
    I think you want [process.exitCode](https://nodejs.org/api/process.html#process_process_exitcode) – Julian de Bhal Feb 26 '16 at 06:08
  • For the record: I spent a good chunk of the day trying to get `process.exitCode` to work for me in a command-line tool I'm building (tested on Node v4.3.0). But I couldn't get it to behave as documented. This very well could have been an edge case with `commander`- although https://github.com/tj/commander.js/search?utf8=%E2%9C%93&q=process.exitCode makes me wonder. Not sure if anyone else out there's seen this problem w/ Node 4, but documenting just in case for future reference. – mikermcneil Aug 27 '16 at 02:31
  • re the possibility of this coming from commander, I also looked at its only dep (https://github.com/zhiyelee/graceful-readlink/search?utf8=%E2%9C%93&q=process.exitCode+OR+process.exit&type=Code) but no dice. Only possible culprit seems like maybe: https://github.com/tj/commander.js/blob/c6236d9504b60d9a2e6aa7fc3ce17a12f48f4a3e/index.js#L554 Specifically, the issue is that, even if you set `process.exitCode = 1`, the process exits with code 0. – mikermcneil Aug 27 '16 at 02:32
11

As @Dominic pointed out, throwing an uncaught error is better practice instead of calling process.exit([code]):
process.exitCode = 1; throw new Error("my module xx condition failed");

MANN
  • 2,686
  • 1
  • 12
  • 17
  • 4
    Taken in context of the question "How to exit in Node.js", this is horrible advice. Your suggestion would make much more sense if the question were specifically asking how to exit on error. I strongly suggest that you word your response in such a way as to indicate that the user do as you suggest, only if they are trying to exit the application in the event of an *error*. – rstackhouse Aug 02 '16 at 14:07
  • @rstackhouse, I hope you have gone through __throwing an uncaught error__ which points to --> https://nodejs.org/api/process.html#process_process_exit_code – MANN Aug 02 '16 at 14:38
  • 5
    The problem with throwing is the ugly as hell stack trace. Any tip to avoid this stack trace (not relevant when CLI tool wants to exit if usage is not correct)? – MoOx Sep 05 '16 at 08:08
11

Press Ctrl + C twice or .exit.

> 
(To exit, press ^C again or type .exit)
> 
HeadAndTail
  • 758
  • 6
  • 8
10

To exit

let exitCode = 1;
process.exit(exitCode)

Useful exit codes

1 - Catchall for general errors
2 - Misuse of shell builtins (according to Bash documentation)
126 - Command invoked cannot execute
127 - “command not found”
128 - Invalid argument to exit
128+n - Fatal error signal “n”
130 - Script terminated by Control-C
255\* - Exit status out of range
Denis Lisitskiy
  • 1,127
  • 9
  • 13
  • Consider updating your answer, https://nodejs.org/api/process.html#process_process_exit_code – Cmag Sep 13 '17 at 18:26
7

From code you can use process.exit([errorcode]) where [errorcode] is an optional integer (0 is the default to indicate success).

If you're using the Read Eval Print Loop (REPL), you can use Ctrl + D, or type .exit

Alternatively, on Windows or Linux you can use Ctrl + C, Ctrl + C

On Mac the command is Ctrl + Z, Ctrl + Z

zzzzBov
  • 157,699
  • 47
  • 307
  • 349
  • 2
    Two control c's works on the mac, too, at least on mine with `node --version` `v0.10.18` – msouth Aug 22 '14 at 17:07
  • Control-C doesn't appear to cancel operations that were already scheduled, whereas ctrl-z kills the process without delay, on Mac. – jorisw Dec 23 '19 at 18:06
3

I was able to get all my node processes to die directly from the Git Bash shell on Windows 10 by typing taskkill -F -IM node.exe - this ends all the node processes on my computer at once. I found I could also use taskkill //F //IM node.exe. Not sure why both - and // work in this context. Hope this helps!

Alison Stuart
  • 51
  • 1
  • 5
2

Open the command line terminal where node application is running and press Ctrl + C

if you want to exit a node js application from code,

process.exit(); // graceful termination 
process.exit(1); // non graceful termination 
Shekar Mania
  • 189
  • 2
  • 5
2

As process is global object, you don't need to import any module. The following function exits or kills the current node process.

process.exit(code)

process.kill(process.pid)

process.abort()

sumit_suthar
  • 392
  • 1
  • 12
1
import mongosse from 'mongoose'
import dotenv from 'dotenv'
import colors from 'colors'
import users from './data/users.js'
import products from './data/products.js'
import User from './models/userModel.js'
import Product from './models/productModel.js'
import Order from './models/orderModel.js'
import connectDB from './config/db.js'

dotenv.config()

connectDB()

const importData = async()=>{
try{
    await Order.deleteMany()
    await Product.deleteMany()
    await User.deleteMany()

    const createdUsers = await User.insertMany(users)
    const adiminUser = createdUsers[0]._id

    sampleProducts = products.map(product =>{
        return {...product, user:adiminUser }
    })
    await Product.insertMany(sampleProducts)

    console.log('Data Imported!'.green.inverse)
    process.exit()      //success and exit

}catch(error){
    consolele.log(`${error}`.red.inverse)
    process.exit(1)   //error and exit

}

}

so here im populating some collections in a db and in the try block if i dont get any errors then we exit it with a success message , so for that we use process.exit() with nothing in the parameter. If theres an error then we need to exit with an unsuccessfull message so we pass 1 in the parameter like this , process.exit(1).

extra: Here by exiting we mean exiting that typical node js program. eg if this code was in a file called dbOperations.js then the process.exit will exit and wont run any code that follows after process.exit

Rmcr714
  • 101
  • 3
  • 6
1

adding

process.exit(1);

will do the trick for you

amir yeganeh
  • 171
  • 3
  • 15
0

if you want to exit from node js application then write

process.exit(1)

in your code

Ishank
  • 2,722
  • 26
  • 43
  • 3
    1 is used to indicate there's been an error in the application, which the other answers already clarify. – Herick Nov 15 '17 at 19:07
0

The exit in node js is done in two ways:

  • Calling process.exit() explicitly.
  • Or, if nodejs event loop is done with all tasks, and there is nothing left to do. Then, the node application will automatically exit.

How it works?

If you want to force the execution loop to stop the process, yo can use the global variable process which is an instance of EventEmitter. So when you call process.exit() you actually emit the exit event that ends all tasks immediately even if there still are asynchronous operations not been done.

process.exit() takes an exit code (Integer) as a parameter. The code 0 is the default and this means it exit with a 'success'. While the code 1 means it exit with a 'failure'.

Community
  • 1
  • 1
majid jiji
  • 334
  • 2
  • 7
-1

If you're in Windows, go to Task Manager, then go to Processes, look for a process called "node", then click on it with the right button of your mouse and then click the "End Process" option.

Albos Hajdari
  • 79
  • 1
  • 11
-2

You may use process.exit([code]) function.

If you want to exit without a 'failure', you use code 0:

process.exit(0);

To exit with a 'failure' code 1 you may run:

process.exit(1);

The 'failure' code of the failure is specific to the application. So you may use your own conventions for it.

Oleksii Trekhleb
  • 1,795
  • 16
  • 21