/ Programming

Dealing with Python-Version Exceptions When Using node-gyp

I was trying to install a JavaScript library called numjs (basically, a JS equivalent to numpy), when I got the following exception:

# Executing the following command...
$ npm install numjs --save

# resulted in ...
gyp ERR! stack Error: spawn EACCES
gyp ERR! stack     at exports._errnoException (util.js:1028:11)
gyp ERR! stack     at ChildProcess.spawn (internal/child_process.js:313:11)
gyp ERR! stack     at exports.spawn (child_process.js:387:9)
gyp ERR! stack     at PythonFinder.exports.execFile (child_process.js:148:15)
gyp ERR! stack     at PythonFinder.checkPythonVersion

For those unfamiliar with node-gyp, this is node's default way of building native Node addons.
Node native addons are:

dynamically-linked shared objects, written in C or C++, that can be loaded into Node.js using the require() function, and used just as if they were an ordinary Node.js module.They are used primarily to provide an interface between JavaScript running in Node.js and C/C++ libraries.
via C/C++ Addons | Node.js v7.6.0 Documentation

In simpler terms, our library, or any of its dependencies tried to build a native addon, and the native build tool failed with the aforementioned exception. Turns out, node-gyp is pretty strict about the version of Python running on your machine. It requires Python 2.7, while it might be that you are running Python 3 already, or have multiple ones that you are alternating between (as in my case).

I solved my particular problem by applying a --python=<PATH_TO_PYTHON2_EXECUTABLE> parameter to the npm install command:

$ npm install numjs --save --python=<PATH_TO_PYTHON2_EXECUTABLE>

To make the changes persistent, however, the documentation suggests to add the python version to the module configuration:

$ npm config set python <PATH_TO_PYTHON2_EXECUTABLE>

or add it to the .npmrc file.