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

旧街凉风 提交于 2019-12-02 17:26:27
Jacob Krall

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();

Although it looks like there's no right answer to this question, so far we have 3 possible hacks and I honestly think my approach is the less intrusive one:

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

This will set an interval that will fire approximately once every 12 days.

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

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

Joe's:

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'll throw another hack into the mix. Here's how to do it with Promise

new Promise(_ => null)

Throw that at the bottom of your .js file and it should run forever.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!