Skip to content

Commit 45c12d7

Browse files
committed
docs: Clarify script working directory behavior (fixes #8305)
1 parent 85a3582 commit 45c12d7

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

docs/lib/content/using-npm/scripts.md

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,22 @@ Reasons for a package removal include:
228228

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

231+
### Working Directory for Scripts
232+
233+
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.
234+
235+
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.
236+
237+
#### Historical Behavior in Older npm Versions
238+
239+
In npm v7 and later, scripts are always executed from the root of the package folder, regardless of your current working directory. This behavior is now reliable and consistent.
240+
241+
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()).
242+
243+
For more details, see:
244+
- [npm v7 release notes](https://github.com/npm/cli/releases/tag/v7.0.0)
245+
- [Discussion about script working directory reliability in npm v6 and earlier](https://github.com/npm/npm/issues/12356)
246+
231247
### User
232248

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

359371
### See Also
360372

361373
* [npm run](/commands/npm-run)
362374
* [package.json](/configuring-npm/package-json)
363375
* [npm developers](/using-npm/developers)
364-
* [npm install](/commands/npm-install)
376+
* [npm install](/commands/npm-install)

0 commit comments

Comments
 (0)