web-dev-qa-db-ja.com

Node.jsでPHP die()と同等のものは何ですか

Node.jsでのPHP die() とは何ですか?

42
PHPst

process.exit() は同等の呼び出しです。

57
Uli Köhler

throwを使用します。スローすると、現在の要求が終了し、ノードプロセスは終了しません。エラービューを使用してその出力をキャッチできます。

throw new Error('your die message here');
17
Anuraag Vaidya

(stdoutではなく)stderrにレポートし、ゼロ以外のステータスで終了してdie()になる必要があります...

function die (errMsg) 
{
    if (errMsg)
        console.error(errMsg);
    process.exit(1);
}
6
ekerner

関数内にない場合は、以下を使用できます。

_return;
_

しかし @UliKöhler の提案を使用することもできます:

_process.exit();
_

いくつかの違いがあります:

  • returnはより優雅に終わります。 process.exit()より突然。
  • returnは、process.exit()のように終了コードを設定しません。

例:

_try {
    process.exitCode = 1;
    return 2;
}
finally {
    console.log('ending it...'); // this is shown
}
_

これにより、コンソールに_ending it..._が出力され、終了コード1で終了します。

_try {
    process.exitCode = 1;
    process.exit(2);
}
finally {
    console.log('ending it...'); // this is not shown
}
_

これはコンソールに何も出力せず、終了コード2で終了します。

5
nl-x