Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forcibly keep a Node.js process from terminating?

People also ask

How do I stop a node JS execution?

Method 1: Using the Ctrl+C key This shortcut can be used to stop any running process by hitting this command on terminal.

How do I stop a NPM process?

To stop a running npm process, press CTRL + C or close the shell window.


The simplest, least intrusive solution

I honestly think my approach is the least intrusive one:

setInterval(() => {}, 1 << 30);

This will set a harmless interval that will fire approximately once every 12 days, effectively doing nothing, but keeping the process running.

Originally, my solution used Number.POSITIVE_INFINITY as the period, so the timer would actually never fire, but this behavior was recently changed by the API and now it doesn't accept anything greater than 2147483647 (i.e., 2 ** 31 - 1). See docs here and here.


Comments on other solutions

For reference, here are the other two answers given so far:

Joe's (deleted since then, but perfectly valid):

require('net').createServer().listen();

Will create a "bogus listener", as he called it. A minor downside is that we'd allocate a port just for that.

Jacob's:

process.stdin.resume();

Or the equivalent:

process.stdin.on("data", () => {});

Puts stdin into "old" mode, a deprecated feature that is still present in Node.js for compatibility with scripts written prior to Node.js v0.10 (reference).

I'd advise against it. Not only it's deprecated, it also unnecessarily messes with stdin.


Use "old" Streams mode to listen for a standard input that will never come:

// Start reading from stdin so we don't exit.
process.stdin.resume();