diff --git a/doc/api/cli.md b/doc/api/cli.md index 4d8e806723866d..f8e4922b30656f 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -997,6 +997,9 @@ changes: Evaluate the following argument as JavaScript. The modules which are predefined in the REPL can also be used in `script`. +If `script` starts with `-`, pass it using `=` (for example, +`node --print --eval=-42`) so it is parsed as the value of `--eval`. + On Windows, using `cmd.exe` a single quote will not work correctly because it only recognizes double `"` for quoting. In Powershell or Git bash, both `'` and `"` are usable. diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index 8d765f10fbcbdb..414344d07cf185 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -115,6 +115,26 @@ child.exec(...common.escapePOSIXShell`"${process.execPath}" -p "\\-42"`, common. assert.strictEqual(stderr, ''); })); +// Eval expressions that start with '-' can be passed with '='. +child.exec(...common.escapePOSIXShell`"${process.execPath}" --print --eval=-42`, common.mustSucceed((stdout, stderr) => { + assert.strictEqual(stdout, '-42\n'); + assert.strictEqual(stderr, ''); +})); + +// Edge case: negative zero should preserve its sign when printed. +child.exec(...common.escapePOSIXShell`"${process.execPath}" --print --eval=-0`, common.mustSucceed((stdout, stderr) => { + assert.strictEqual(stdout, '-0\n'); + assert.strictEqual(stderr, ''); +})); + +// Nearby-path safety: option-looking values should still be rejected with -e. +child.exec(...common.escapePOSIXShell`"${process.execPath}" -e -p`, common.mustCall((err, stdout, stderr) => { + assert.strictEqual(err.code, 9); + assert.strictEqual(stdout, ''); + assert.strictEqual(stderr.trim(), + `${process.execPath}: -e requires an argument`); +})); + // Long output should not be truncated. child.exec(...common.escapePOSIXShell`"${process.execPath}" -p "'1'.repeat(1e5)"`, common.mustSucceed((stdout, stderr) => { assert.strictEqual(stdout, `${'1'.repeat(1e5)}\n`);