如何在Node.js中退出进程
在本文中,我们将看到如何在NodeJS应用程序中退出。有不同类型的方法可以退出Nodejs应用程序,这里我们讨论了以下四种方法。
方法1:使用ctrl+C键: 在控制台中运行NodeJS程序时,您可以直接从控制台关闭它使用 ctrl+C ,并更改下面显示的代码:
方法2:使用 process.exit() 函数: 此函数告诉 Node.js 结束与当前进程同时运行的进程,并返回一个退出码。调用此函数将强制 Node.js 尽快退出当前正在运行的进程。
语法:
process.exit(code)
参数: 此函数接受如上所述并在下方描述的单个参数:
- code: 它可以是0或1值。这里0表示在没有任何失败的情况下结束进程,而1表示以某种失败方式结束进程。
app.js
// An empty array.
var arr = [];
// Variable a and b
var a = 8;
var b = 2;
// While condition to run loop
// infinite times
while (a != 0 || b != 0) {
// Increment then value
// of a and b
a = a + 1;
b = b + 2;
// Push the sum of a and b
// into array
arr.push(a + b);
// If a and b become equal it
// will exit the process
if (a == b) {
console.log("The process will "
+ "exit when a and b become equal");
process.exit(0);
console.log("Complete Process")
}
// It will print the result when
// a and is not equal
else {
console.log(arr);
}
}
输出:
方法3:使用process.exitCode变量: 另一种方法是使用process.exitCode变量来设置process.exitCode值,这将允许Node.js程序自行退出而不会留下未来的进一步调用。这种方法更安全,会减少Node.js代码中的问题。
app.js
// An empty array.
var arr = [];
// Variable a and b
var a = 8;
var b = 2;
// While condition to run
// loop infinite times
while (a > b) {
// Increment then value
// of a and b
a = a + 1;
b = b + 2;
// Push the sum of a and
// b into array
arr.push(a + b);
// If a and b become equal
// it will exit the process
if (a == b) {
console.log("The process will "
+ "exit when a and b become equal");
process.exitCode = 0;
console.log("Complete Process")
}
// It will print the result when
// a and is not equal
else {
console.log(arr);
}
}
输出:
方法4:使用process.on()函数: Process对象 是一个全局变量,它让我们可以管理当前的Node.js进程,当程序执行到代码行的末尾时,进程将自动退出,我们不需要使用require来引入Process对象,因为它在Node.js中自动存在。
app.js
console.log('Code is running');
process.on('exit', function (code) {
return console.log(`Process to exit with code ${code}`);
});
输出: