Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change working directory for npm scripts

Q: Is it possible to change the the context in which npm runs scripts?

What I want to is the following:

"scripts": {    "test": "gulp mocha",    "pre-install": "./deps/2.7/cpython/configure --prefix=$(pwd)/build --exec-prefix=$(pwd)/build && make -C deps/2.7/cpython && make -C deps/2.7/cpython install",    "install": "node-gyp rebuild" }, 

Obviously cd deps/2.7/cpython/ && ./configure would work on UNIX-like systems but not on windows.

Why: The root of the problem is, that the configure command of the python repo outputs files into the directory where it is called. The files however are build relevant for make and make install which look for the files in the directory of the repo.

In this case I can't change the Makefile since the build process of Python is understandably complex.

Alternative: The alternative is probably to write some install.js and use node's OS independent API and some child_process.exec(), which I am probably gonna do. However, not leaving npm would be really nice.

like image 612
eljefedelrodeodeljefe Avatar asked May 17 '15 11:05

eljefedelrodeodeljefe


People also ask

How do I change the working directory in Node JS?

You can change the current working directory of the Node process through the command process. chdir() . var process = require('process'); process. chdir('../');

What folder to run npm install?

You should run it in your project root folder, or the folder above your node_modules folder as sometimes the structure can differentiate between projects. But in general: the root folder of your project, as long as it is one folder above your node_modules.


2 Answers

npm allows only to do cd dir && command -args, which will also run on Windows.

A change to use node's spawn functionality has been made in PR https://github.com/npm/npm/pull/10958, but was rejected, due to the above solution.

like image 115
eljefedelrodeodeljefe Avatar answered Nov 15 '22 22:11

eljefedelrodeodeljefe


As noted above:

npm is probably using

var spawn = require('child_process').spawn 

which would allow you to set options like:

    {cwd: pwd + 'somepath'} 

but isn't exposing it.

I've solved it with a fairly large install.js, which does roughly that and it gets called from package.json like above. The API of child_process isn't that easy to handle, though, since it throws loads of hard to debug errors. Took me some time, but I am happy now.

like image 32
Paul Sweatte Avatar answered Nov 15 '22 23:11

Paul Sweatte