no-process-exit

禁止使用 process.exit()

该规则在 ESLint v7.0.0 中已弃用。请使用 eslint-plugin-n 中的相应规则。

¥This rule was deprecated in ESLint v7.0.0. Please use the corresponding rule in eslint-plugin-n.

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 中引入。

资源

ESLint 中文网
粤ICP备13048890号