Scott Lin
Scott Lin

Reputation: 1562

cwd not respected when spawning Node child process

I'm trying to spawn a synchronous child process using Node v11.1.0 and set the current working directory as below. I'm using Windows 10.

const options = {
  cwd: 'D:\\somepath\\node_modules\\.install-npm-version-temp-U9EUNd',
  stdio: 'inherit'
};
const command = process.platform === 'win32' ? 'npm.cmd' : 'npm';
childProcess.spawnSync(command, ['install', '[email protected]'], options);

The parent process current working directory is 'D:\\somepath' in this example.

After the child process has finished executing, I expect [email protected] to be installed to the cwd set above, but it is not. Instead, it is being installed in 'D:\\somepath\\node_modules', which leads me to believe the current working directory of the child process is really the parent's current working directory. Further evidence to suggest this is, 'D:\\somepath\\package.json' is modified as a result of the child process running to contain dependency [email protected] (it was not there in prior).

Note, the cwd path above is valid on my machine. The NPM command executes and reports success.

Based on the Node docs, I believe I'm using the spawnSync API correctly, but I'm having no luck debugging this. Any suggestions?

Upvotes: 1

Views: 1084

Answers (1)

lucascaro
lucascaro

Reputation: 19277

You have a package.json file in D:\somepath and not in your cwd.

From the npm docs:

When installing locally, npm first tries to find an appropriate prefix folder. This is so that npm install [email protected] will install to the sensible root of your package, even if you happen to have cded into some other folder.

Starting at the $PWD, npm will walk up the folder tree checking for a folder that contains either a package.json file, or a node_modules folder. If such a thing is found, then that is treated as the effective "current directory" for the purpose of running npm commands. (This behavior is inspired by and similar to git's .git-folder seeking logic when running git commands in a working dir.)

If no package root is found, then the current folder is used.

Upvotes: 4

Related Questions