Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

process: argv1 property to preserve original argv[1] #49918

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions doc/api/process.md
Original file line number Diff line number Diff line change
Expand Up @@ -958,6 +958,32 @@ $ bash -c 'exec -a customArgv0 ./node'
'customArgv0'
```

## `process.argv1`

<!-- YAML
added: REPLACEME
-->

* {string | undefined}

The `process.argv1` property stores a read-only copy of the original value of
`argv[1]` passed when Node.js starts.
GeoffreyBooth marked this conversation as resolved.
Show resolved Hide resolved

```js
// test.js
console.log('argv1 ', process.argv1);
console.log('argv[1]', process.argv[1]);
```

```console
$ node ./test.js
argv1 ./test.js
argv[1] /absolute/path/to/test.js
```

`process.argv1` is `undefined` for cases where Node.js is run without a main
entry point (such as `node --eval`) and within worker threads.

## `process.channel`

<!-- YAML
Expand Down
17 changes: 9 additions & 8 deletions lib/internal/main/run_main_module.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,18 @@ const {
markBootstrapComplete,
} = require('internal/process/pre_execution');

prepareMainThreadExecution(true);
const mainEntry = prepareMainThreadExecution(true);

markBootstrapComplete();

// Necessary to reset RegExp statics before user code runs.
RegExpPrototypeExec(/^/, '');

// Note: this loads the module through the ESM loader if the module is
// determined to be an ES module. This hangs from the CJS module loader
// because we currently allow monkey-patching of the module loaders
// in the preloaded scripts through require('module').
// runMain here might be monkey-patched by users in --require.
// XXX: the monkey-patchability here should probably be deprecated.
require('internal/modules/cjs/loader').Module.runMain(process.argv[1]);
/**
* To support legacy monkey-patching of `Module.runMain`, we call `runMain` here to have the CommonJS loader begin
* the execution of the main entry point, even if the ESM loader immediately takes over because the main entry is an
* ES module or one of the other opt-in conditions (such as the use of `--import`) are met. Users can monkey-patch
* before the main entry point is loaded by doing so via scripts loaded through `--require`. This monkey-patchability
* is undesirable and should be deprecated.
*/
require('internal/modules/cjs/loader').Module.runMain(mainEntry);
9 changes: 5 additions & 4 deletions lib/internal/modules/run_main.js
GeoffreyBooth marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ function resolveMainPath(main) {

/**
* Determine whether the main entry point should be loaded through the ESM Loader.
* @param {string} mainPath Absolute path to the main entry point
* @param {string} mainPath - Absolute path to the main entry point
*/
function shouldUseESMLoader(mainPath) {
/**
Expand All @@ -53,7 +53,7 @@ function shouldUseESMLoader(mainPath) {

/**
* Run the main entry point through the ESM Loader.
* @param {string} mainPath Absolute path to the main entry point
* @param {string} mainPath - Absolute path for the main entry point
*/
function runMainESM(mainPath) {
const { loadESM } = require('internal/process/esm_loader');
Expand All @@ -68,7 +68,7 @@ function runMainESM(mainPath) {

/**
* Handle process exit events around the main entry point promise.
* @param {Promise} promise Main entry point promise
* @param {Promise} promise - Main entry point promise
*/
async function handleMainPromise(promise) {
const {
Expand All @@ -86,7 +86,8 @@ async function handleMainPromise(promise) {
* Parse the CLI main entry point string and run it.
* For backwards compatibility, we have to run a bunch of monkey-patchable code that belongs to the CJS loader (exposed
* by `require('module')`) even when the entry point is ESM.
* @param {string} main CLI main entry point string
* Because of backwards compatibility, this function is exposed publicly via `import { runMain } from 'node:module'`.
* @param {string} main - Resolved absolute path for the main entry point, if found
*/
function executeUserEntryPoint(main = process.argv[1]) {
const resolvedMain = resolveMainPath(main);
Expand Down
51 changes: 44 additions & 7 deletions lib/internal/process/pre_execution.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ function prepareExecution(options) {
refreshRuntimeOptions();
reconnectZeroFillToggle();

// Patch the process object with legacy properties and normalizations
patchProcessObject(expandArgv1);
// Patch the process object and get the resolved main entry point.
const mainEntry = patchProcessObject(expandArgv1);
setupTraceCategoryState();
setupInspectorHooks();
setupWarningHandler();
Expand Down Expand Up @@ -131,6 +131,8 @@ function prepareExecution(options) {
if (initializeModules) {
setupUserModules();
}

return mainEntry;
}

function setupSymbolDisposePolyfill() {
Expand Down Expand Up @@ -176,12 +178,21 @@ function refreshRuntimeOptions() {
refreshOptions();
}

/**
* Patch the process object with legacy properties and normalizations.
* Replace `process.argv[0]` with `process.execPath`, preserving the original `argv[0]` value as `process.argv0`.
* Replace `process.argv[1]` with the resolved file path of the entry point, if requested and a replacement can be
* found; preserving the original value as `process.argv1`.
* @param {boolean} expandArgv1 - Whether to replace `process.argv[1]` with the resolved file path of the main entry
* point.
*/
function patchProcessObject(expandArgv1) {
const binding = internalBinding('process_methods');
binding.patchProcessObject(process);

require('internal/process/per_thread').refreshHrtimeBuffer();

// Since we replace process.argv[0] below, preserve the original value in case the user needs it.
ObjectDefineProperty(process, 'argv0', {
__proto__: null,
enumerable: true,
Expand All @@ -190,16 +201,27 @@ function patchProcessObject(expandArgv1) {
value: process.argv[0],
});

// Since we usually replace process.argv[1] below, preserve the original value in case the user needs it.
ObjectDefineProperty(process, 'argv1', {
__proto__: null,
enumerable: true,
// Only set it to true during snapshot building.
configurable: isBuildingSnapshot(),
value: process.argv[1],
});

process.exitCode = undefined;
process._exiting = false;
process.argv[0] = process.execPath;

if (expandArgv1 && process.argv[1] &&
!StringPrototypeStartsWith(process.argv[1], '-')) {
// Expand process.argv[1] into a full path.
const path = require('path');
// If a requested, update process.argv[1] to replace whatever the user provided with the resolved absolute URL or file
// path of the entry point.
/** @type {ReturnType<determineMainEntry>} */
let mainEntry;
if (expandArgv1) {
mainEntry = determineMainEntry(process.argv[1]);
try {
process.argv[1] = path.resolve(process.argv[1]);
process.argv[1] = mainEntry;
} catch {
// Continue regardless of error.
}
Expand All @@ -226,6 +248,21 @@ function patchProcessObject(expandArgv1) {
addReadOnlyProcessAlias('traceDeprecation', '--trace-deprecation');
addReadOnlyProcessAlias('_breakFirstLine', '--inspect-brk', false);
addReadOnlyProcessAlias('_breakNodeFirstLine', '--inspect-brk-node', false);

return mainEntry;
}

/**
* For non-STDIN input, we need to resolve what was specified on the command line into a path.
* @param {string} input - What was specified on the command line as the main entry point.
*/
function determineMainEntry(input = process.argv[1]) {
if (!input || StringPrototypeStartsWith(input, '-')) { // STDIN
return undefined;
}
// Expand the main entry point into a full path.
const { resolve } = require('path');
return resolve(input);
}

function addReadOnlyProcessAlias(name, option, enumerable = true) {
Expand Down
2 changes: 2 additions & 0 deletions test/fixtures/process-argv1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
console.log(process.argv1);
console.log(process.argv[1]);
25 changes: 25 additions & 0 deletions test/parallel/test-process-argv1.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { spawnPromisified } from '../common/index.mjs';
import * as fixtures from '../common/fixtures.mjs';
import { strictEqual } from 'node:assert';
import { describe, it } from 'node:test';
import { dirname } from 'node:path';

describe('process.argv1', { concurrency: true }, () => {
it('should be the string for the entry point before the entry was resolved into an absolute path', async () => {
const fixtureRelativePath = './process-argv1.js';
const fixtureAbsolutePath = fixtures.path(fixtureRelativePath);

const { code, signal, stdout, stderr } = await spawnPromisified(process.execPath, [fixtureRelativePath], {
cwd: dirname(fixtureAbsolutePath),
anonrig marked this conversation as resolved.
Show resolved Hide resolved
});

strictEqual(stderr, '');
deepStrictEqual(stdout.split('\n'), [

Check failure on line 17 in test/parallel/test-process-argv1.mjs

View workflow job for this annotation

GitHub Actions / lint-js-and-md

'deepStrictEqual' is not defined

Check failure on line 17 in test/parallel/test-process-argv1.mjs

View workflow job for this annotation

GitHub Actions / test-asan

--- stdout --- ::debug::starting to run process.argv1 ▶ process.argv1 ✖ should be the string for the entry point before the entry was resolved into an absolute path (199.835821ms) ReferenceError: deepStrictEqual is not defined at TestContext.<anonymous> (file:///home/runner/work/node/node/test/parallel/test-process-argv1.mjs:17:5) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Test.run (node:internal/test_runner/test:632:9) at async Promise.all (index 0) at async Suite.run (node:internal/test_runner/test:948:7) at async startSubtest (node:internal/test_runner/harness:216:3) ▶ process.argv1 (220.199988ms) ::debug::starting to run should be the string for the entry point before the entry was resolved into an absolute path ::error title=should be the string for the entry point before the entry was resolved into an absolute path,file=test/parallel/test-process-argv1.mjs,line=17,col=5::Error [ERR_TEST_FAILURE]: deepStrictEqual is not defined at async Promise.all (index 0) { code: 'ERR_TEST_FAILURE', failureType: 'testCodeFailure', cause: ReferenceError: deepStrictEqual is not defined at TestContext.<anonymous> (file:///home/runner/work/node/node/test/parallel/test-process-argv1.mjs:17:5) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Test.run (node:internal/test_runner/test:632:9) at async Promise.all (index 0) at async Suite.run (node:internal/test_runner/test:948:7) at async startSubtest (node:internal/test_runner/harness:216:3) } ℹ tests 1 ℹ suites 1 ℹ pass 0 ℹ fail 1 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 322.001123 ✖ failing tests: test at file:/home/runner/work/node/node/test/parallel/test-process-argv1.mjs:8:3 ✖ should be the string for the entry point before the entry was resolved into an absolute path (199.835821ms) ReferenceError: deepStrictEqual is not defined at TestContext.<anonymous> (file:///home/runner/work/node/node/test/parallel/test-process-argv1.mjs:17:5) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Test.run (node:internal/test_runner/test:632:9) at async Promise.all (index 0) at async Suite.run (node:internal/test_runner/test:948:7) at async startSubtest (node:internal/test_runner/harness:216:3) ::group::Test results (0 passed, 1 failed) ::notice::Total Tests: 1 Suites 📂: 1 Passed ✅: 0 Failed ❌: 1 Canceled 🚫: 0 Skipped ⏭️: 0 Todo 📝: 0 Duration 🕐: 322.001ms ::endgroup:: Command: out/Release/node --test-reporter=spec --test-reporter-destination=stdout --test-reporter=./tools/github_reporter/index.js --test-reporter-destination=stdout /home/runner/work/node/node/test/parallel/test-process-argv1.mjs

Check failure on line 17 in test/parallel/test-process-argv1.mjs

View workflow job for this annotation

GitHub Actions / test-linux

--- stdout --- ::debug::starting to run process.argv1 ▶ process.argv1 ✖ should be the string for the entry point before the entry was resolved into an absolute path (45.781296ms) ReferenceError: deepStrictEqual is not defined at TestContext.<anonymous> (file:///home/runner/work/node/node/test/parallel/test-process-argv1.mjs:17:5) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Test.run (node:internal/test_runner/test:632:9) at async Promise.all (index 0) at async Suite.run (node:internal/test_runner/test:948:7) at async startSubtest (node:internal/test_runner/harness:216:3) ▶ process.argv1 (50.88534ms) ::debug::starting to run should be the string for the entry point before the entry was resolved into an absolute path ::error title=should be the string for the entry point before the entry was resolved into an absolute path,file=test/parallel/test-process-argv1.mjs,line=17,col=5::Error [ERR_TEST_FAILURE]: deepStrictEqual is not defined at async Promise.all (index 0) { code: 'ERR_TEST_FAILURE', failureType: 'testCodeFailure', cause: ReferenceError: deepStrictEqual is not defined at TestContext.<anonymous> (file:///home/runner/work/node/node/test/parallel/test-process-argv1.mjs:17:5) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Test.run (node:internal/test_runner/test:632:9) at async Promise.all (index 0) at async Suite.run (node:internal/test_runner/test:948:7) at async startSubtest (node:internal/test_runner/harness:216:3) } ℹ tests 1 ℹ suites 1 ℹ pass 0 ℹ fail 1 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 77.512293 ✖ failing tests: test at file:/home/runner/work/node/node/test/parallel/test-process-argv1.mjs:8:3 ✖ should be the string for the entry point before the entry was resolved into an absolute path (45.781296ms) ReferenceError: deepStrictEqual is not defined at TestContext.<anonymous> (file:///home/runner/work/node/node/test/parallel/test-process-argv1.mjs:17:5) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Test.run (node:internal/test_runner/test:632:9) at async Promise.all (index 0) at async Suite.run (node:internal/test_runner/test:948:7) at async startSubtest (node:internal/test_runner/harness:216:3) ::group::Test results (0 passed, 1 failed) ::notice::Total Tests: 1 Suites 📂: 1 Passed ✅: 0 Failed ❌: 1 Canceled 🚫: 0 Skipped ⏭️: 0 Todo 📝: 0 Duration 🕐: 77.512ms ::endgroup:: Command: out/Release/node --test-reporter=spec --test-reporter-destination=stdout --test-reporter=./tools/github_reporter/index.js --test-reporter-destination=stdout /home/runner/work/node/node/test/parallel/test-process-argv1.mjs

Check failure on line 17 in test/parallel/test-process-argv1.mjs

View workflow job for this annotation

GitHub Actions / test-macOS

--- stdout --- ::debug::starting to run process.argv1 ▶ process.argv1 ✖ should be the string for the entry point before the entry was resolved into an absolute path (48.318554ms) ReferenceError: deepStrictEqual is not defined at TestContext.<anonymous> (file:///Users/runner/work/node/node/test/parallel/test-process-argv1.mjs:17:5) at async Test.run (node:internal/test_runner/test:632:9) at async Promise.all (index 0) at async Suite.run (node:internal/test_runner/test:948:7) at async startSubtest (node:internal/test_runner/harness:216:3) ▶ process.argv1 (52.772692ms) ::debug::starting to run should be the string for the entry point before the entry was resolved into an absolute path ::error title=should be the string for the entry point before the entry was resolved into an absolute path,file=test/parallel/test-process-argv1.mjs,line=17,col=5::Error [ERR_TEST_FAILURE]: deepStrictEqual is not defined at async Promise.all (index 0) { code: 'ERR_TEST_FAILURE', failureType: 'testCodeFailure', cause: ReferenceError: deepStrictEqual is not defined at TestContext.<anonymous> (file:///Users/runner/work/node/node/test/parallel/test-process-argv1.mjs:17:5) at async Test.run (node:internal/test_runner/test:632:9) at async Promise.all (index 0) at async Suite.run (node:internal/test_runner/test:948:7) at async startSubtest (node:internal/test_runner/harness:216:3) } ℹ tests 1 ℹ suites 1 ℹ pass 0 ℹ fail 1 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 72.467005 ✖ failing tests: test at file:/Users/runner/work/node/node/test/parallel/test-process-argv1.mjs:8:3 ✖ should be the string for the entry point before the entry was resolved into an absolute path (48.318554ms) ReferenceError: deepStrictEqual is not defined at TestContext.<anonymous> (file:///Users/runner/work/node/node/test/parallel/test-process-argv1.mjs:17:5) at async Test.run (node:internal/test_runner/test:632:9) at async Promise.all (index 0) at async Suite.run (node:internal/test_runner/test:948:7) at async startSubtest (node:internal/test_runner/harness:216:3) ::group::Test results (0 passed, 1 failed) ::notice::Total Tests: 1 Suites 📂: 1 Passed ✅: 0 Failed ❌: 1 Canceled 🚫: 0 Skipped ⏭️: 0 Todo 📝: 0 Duration 🕐: 72.467ms ::endgroup:: Command: out/Release/node --test-reporter=spec --test-reporter-destination=stdout --test-reporter=./tools/github_reporter/index.js --test-reporter-destination=stdout /Users/runner/work/node/node/test/parallel/test-process-argv1.mjs
fixtureRelativePath,
fixtureAbsolutePath,
'',
]);
strictEqual(code, 0);
strictEqual(signal, null);
});
});
Loading