Run npm install in a different directory

Filed under: PowerShell

I find that trying to run NPM install for all dependencies in a different folder than where the package.json resides,… a bit troublesome.

My primary objective for running NPM from a different folder is the use case of using build scripts. It just feels hacky to change the directory away from root working directory for a build.

I’ve seen posts talking using --prefix to accomplish this, however, if I do the following on Windows:

npm install --cwd "c:\path\to\dest" --prefix "c:\path\to\dest"

The dependencies install, but the bin links, like bash scripts and cmd files, are stored in the c:\path\to\dest instead of c:\path\to\dest\node_modules\.bin which one would expect for a local install. So it acts as if you’re doing an install to the global NPM folder.

If you change the target directory for the --prefix flag, it creates a nested hierarchy.

npm install --cwd "c:\path\to\dest" --prefix "c:\path\to\dest2"

The above command will create a .bin folder as expected, however, the node_modules folder you want will be c:\path\to\dest2\node_modules\{projectName}\node_modules\.bin, so you would need run this command setting the prefix to a tmp folder then copy the folder to the correct location, at the cost of extra IO.

The option I’ve settled upon is calling an external process and getting all the output for the external process in the current window. The easiest path to that is calling powershell.exe -Command. The output is sent to the host shell, and the errors are returned as a result variable.

$errors = powershell.exe -Command "cd `"c:\path\to\dest" `n npm install"
if($errors.Length -gt 0)) {
   // handle error

If anyone finds a better way, sound off in the comments below.

Nerdy Mishka