Skip to content

docs: Clarify script working directory behavior (fixes #8305) #8308

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

Merged
Merged
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
19 changes: 14 additions & 5 deletions docs/lib/content/using-npm/scripts.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,20 @@ Reasons for a package removal include:

Due to the lack of necessary context, `uninstall` lifecycle scripts are not implemented and will not function.

### Working Directory for Scripts

Scripts are always run from the root of the package folder, regardless of what the current working directory is when `npm` is invoked. This means your scripts can reliably assume they are running in the package root.

If you want your script to behave differently based on the directory you were in when you ran `npm`, you can use the `INIT_CWD` environment variable, which holds the full path you were in when you ran `npm run`.

#### Historical Behavior in Older npm Versions

For npm v6 and earlier, scripts were generally run from the root of the package, but there were rare cases and bugs in older versions where this was not guaranteed. If your package must support very old npm versions, you may wish to add a safeguard in your scripts (for example, by checking process.cwd()).

For more details, see:
- [npm v7 release notes](https://github.com/npm/cli/releases/tag/v7.0.0)
- [Discussion about script working directory reliability in npm v6 and earlier](https://github.com/npm/npm/issues/12356)

### User

When npm is run as root, scripts are always run with the effective uid
Expand Down Expand Up @@ -350,11 +364,6 @@ file.
preinstall or install script. If you are doing this, please consider if
there is another option. The only valid use of `install` or `preinstall`
scripts is for compilation which must be done on the target architecture.
* Scripts are run from the root of the package folder, regardless of what the
current working directory is when `npm` is invoked. If you want your
script to use different behavior based on what subdirectory you're in, you
can use the `INIT_CWD` environment variable, which holds the full path you
were in when you ran `npm run`.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

Extra space

### See Also

Expand Down
Loading