Index

no-process-exit

禁止使用 process.exit()

Important

This rule was deprecated in ESLint v7.0.0. It will be removed in v11.0.0. Please use the corresponding rule in eslint-plugin-n.

Learn more

在 Node.js 中,process.exit() 方法用于立即停止 Node.js 进程并退出。这是一个危险的操作,因为它可以在任何方法的任何时间发生,可能会在出现错误时完全停止 Node.js 应用。例如:

🌐 The process.exit() method in Node.js is used to immediately stop the Node.js process and exit. This is a dangerous operation because it can occur in any method at any point in time, potentially stopping a Node.js application completely when an error occurs. For example:

if (somethingBadHappened) {
    console.error("Something bad happened!");
    process.exit(1);
}

这段代码可能出现在任何模块中,当 somethingBadHappened 为真值时会停止整个应用。这不会给应用任何机会来应对错误。通常更好的做法是抛出一个错误,并允许应用适当地处理它:

🌐 This code could appear in any module and will stop the entire application when somethingBadHappened is truthy. This doesn’t give the application any chance to respond to the error. It’s usually better to throw an error and allow the application to handle it appropriately:

if (somethingBadHappened) {
    throw new Error("Something bad happened!");
}

通过这种方式抛出错误,应用的其他部分有机会处理该错误,而不是完全停止应用。如果错误一直传递到进程而未被处理,那么进程将退出并返回非零退出代码,因此最终结果是相同的。

🌐 By throwing an error in this way, other parts of the application have an opportunity to handle the error rather than stopping the application altogether. If the error bubbles all the way up to the process without being handled, then the process will exit and a non-zero exit code will returned, so the end result is the same.

如果你仅仅使用 process.exit() 来指定退出代码,你可以改为设置 process.exitCode(在 Node.js 0.11.8 中引入)。

🌐 If you are using process.exit() only for specifying the exit code, you can set process.exitCode (introduced in Node.js 0.11.8) instead.

规则详情

🌐 Rule Details

此规则旨在防止在 Node.js JavaScript 中使用 process.exit()。因此,每当在代码中发现 process.exit() 时,它都会发出警告。

🌐 This rule aims to prevent the use of process.exit() in Node.js JavaScript. As such, it warns whenever process.exit() is found in code.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint no-process-exit: "error"*/

process.exit(1);
process.exit(0);

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint no-process-exit: "error"*/

Process.exit();
var exit = process.exit;

何时不使用

🌐 When Not To Use It

Node.js 应用中可能有一部分负责确定退出时应返回的正确退出码。在这种情况下,你应该关闭此规则以允许正确处理退出码。

🌐 There may be a part of a Node.js application that is responsible for determining the correct exit code to return upon exiting. In that case, you should turn this rule off to allow proper handling of the exit code.

版本

此规则是在 ESLint v0.4.0 中引入。

资源