From 7e24fe6ac65d063d855f7360415c4f3860726467 Mon Sep 17 00:00:00 2001 From: KirtiRamchandani Date: Mon, 25 May 2026 11:53:20 +0530 Subject: [PATCH] docs: explain syncProcessCwd async contexts --- docs/api.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/docs/api.md b/docs/api.md index b69b0f3027..66ef41aaf5 100644 --- a/docs/api.md +++ b/docs/api.md @@ -240,6 +240,49 @@ syncProcessCwd() syncProcessCwd(false) // pass false to disable the hook ``` +Use this when code inside separate async contexts relies on `process.cwd()` or +relative paths in Node APIs. Without the hook, `cd()` still changes the process +directory globally, while `within()` restores only the internal `$` context: + +```js +const start = process.cwd() + +await within(async () => { + cd('/tmp/project') + await fs.pathExists('package.json') // resolves from /tmp/project +}) + +await within(async () => { + process.cwd() // => /tmp/project + await $`pwd` // => start +}) +``` + +With the hook enabled, each async callback gets `process.cwd()` restored from +the `$` context before it runs: + +```js +syncProcessCwd() + +try { + await within(async () => { + cd('/tmp/project') + await fs.pathExists('package.json') // resolves from /tmp/project + }) + + await within(async () => { + process.cwd() // => start + await $`pwd` // => start + }) +} finally { + syncProcessCwd(false) +} +``` + +If only `zx` commands need a different directory, prefer setting `$.cwd` inside +the `within()` callback. Enable `syncProcessCwd()` when non-`zx` code also needs +relative paths to follow that context. + > This feature is disabled by default because of performance overhead. ## `retry()`