Skip to content

fix: preserve process.cwd() after SETLOCAL in cmd shims - #192

Closed
dyk1454683243-sudo wants to merge 1 commit into
npm:mainfrom
dyk1454683243-sudo:cursor/setlocal-cwd-8aeb
Closed

dyk1454683243-sudo wants to merge 1 commit into
npm:mainfrom
dyk1454683243-sudo:cursor/setlocal-cwd-8aeb

Conversation

@dyk1454683243-sudo

Copy link
Copy Markdown

Fixes #69

Cause

Shebang .cmd shims isolate _prog with SETLOCAL, then launch Node with:

endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" ...

goto #_undefined_# is the existing “Terminate Batch Job?” workaround: it leaves batch context so Node is not a child of the .cmd. Leaving that context implied-ENDLOCALs leftover frames.

SETLOCAL saves the current directory as well as the environment. The issue’s parent script is:

setlocal
cd C:\abcdefg\
test.cmd
endlocal

When the shim exits batch context, the parent setlocal is popped too, so the cd is undone and Node’s process.cwd() is the pre-cd directory. Same-line %CD% is still the post-cd path, because cmd.exe expands percents before any command on the line runs.

This is still the generated launch line on current main. No open PR already claimed #69.

Fix

After the goto, re-apply the already-expanded directory:

endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & cd /d "%CD%" & set PATHEXT=... & "%_prog%" ...

cd has to come after goto. A restore before the goto is undone by the implied ENDLOCAL.

Tests

  • Reproduces the issue’s .cmd / SETLOCAL / :find_dp0 / parent setlocal+cd pattern: without cd /d "%CD%" the simulated Node cwd is the pre-cd directory; with it, cwd is C:\abcdefg
  • Generated shebang shims must contain cd /d "%CD%" after goto #_undefined_#
  • Windows-only functional test: parent test.bat does setlocal + cd + shim; aaaa.js writes process.cwd() (skipped on non-Windows CI)
  • Snapshots updated

The goto-undefined launch line exits batch context so leftover SETLOCAL
frames (including a parent setlocal + cd) restore the pre-cd directory
before Node starts. Re-apply %CD% after that exit; it is expanded on
the same line before endLocal runs.

Fixes npm#69

Co-authored-by: David <dyk1454683243-sudo@users.noreply.github.com>
@dyk1454683243-sudo
dyk1454683243-sudo requested a review from a team as a code owner September 20, 2026 18:19
@dyk1454683243-sudo

Copy link
Copy Markdown
Author

Withdrawing this PR while I clean up a high-volume open-PR backlog. Sorry for the noise — happy to come back later with a focused change if useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Reports invalid process.cwd()

2 participants