Got to this post trying to get a correct set-up for node-gyp
, after upgrading Node.js
from v5.X
to v12.X
by overriding previous installation, and upgrading node-gyp
.
It seems fairly easy to miss some step when you already have a Visual Studio
environment and one or more versions of Python
installed.
I will try to synthesise here the steps that worked for me.
CONTEXT
Below the details as per configuration:
+-------+-----------------------------+-------------+-------------------------------------+ | | Component | Name | Version | +-------+-----------------------------+-------------+-------------------------------------+ | (1) | Platform | Windows 10 | NT 10.0.18362 | | (2) | Target run-time environment | Node.js | v12.16.1 | | (3) | Packet Manager | npm | v6.13.4 | | (4) | CLI Toolchain for compiling | node-gyp | v6.0.1 | | (4.a) | Compiler Language | Python | v2.7.0 | | (4.b) | Project Builder | MSBuild.exe | Microsoft (R) Build Engine for .NET | | | | | version 16.2.32702+c4012a063 | | | | | 16.200.19.32702 | +-------+-----------------------------+-------------+-------------------------------------+
Guideline
You might have already walked through some of the steps outlined here. If you incurred in some issues, you may be able to identify at which stage something went wrong by reviewing the steps in detail:
References
node-gyp
on GitHub: README.md (Generate Your Projects)- A Comprehensive Guide to Fixing Node-Gyp Issues on Windows (by Joe Bustamante; March 27, 2019)
- Setting up None.js on Windows 10 (by Ferenc Hámori; May 17, 2016)
- Using Python on Windows (official documentation)
(1) Node.js
This guideline assumes that git
is already installed in your machine (you will find the installer for Windows here anyways).
- Install
Node.js
: download the last LTS version for your platform (Windows Installer.msi
should work)
To verify it is correctly installed, in a test folder, add a file test.js
with this javascript
code: console.log("Node is installed!");
, and in a terminal run: node test.js
. You should be prompted with Node is installed!
.
(2) npm
- upgrade
npm
to the latest stable version using thenpm-windows-upgrade
package
Run as Administrator a PowerShell terminal:
PS C:\WINDOWS\system32> npm-windows-upgrade
You will be prompted to choose a version. The greatest available version among the options should be fine.
If you miss this package you might want to follow the instructions to install it by following the steps outlined in the GitHub repository, which basically are to type the following in a PowerShell console running as Administrator:
PS C:\WINDOWS\system32> Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
PS C:\WINDOWS\system32> npm install --global --production npm-windows-upgrade
PS C:\WINDOWS\system32> npm-windows-upgrade
(3) Visual Studio
If you have Visual Studio
already installed, you might skip this step, unless you wanted to also upgrade to the newest version.
In some posts, you might have read that you can achieve this step by simply using the following command line, after installing node-gyp
:
npm install --global --production windows-build-tools --vs2015
However, you could opt to achieve this by other means:
- you may have already an installation of
Visual Studio
and just want to configurenode-gyp
to use it - you may prefer to do a separated installation of
Visual Studio
and later on configurenode-gyp
to use it
This is really up to you. At a later stage, in this guideline, we will walk through the steps to configure the node-gyp
to use a specific Visual Studio
version.
(4) Python
In the installation guideline for node-gyp
(GitHub official repo) specifies which versions of Python
are currently compatible with the latest node-gyp
version on Unix and macOS. However it does not explain for Windows platforms (as at 1st of March 2020).
Although lack of documentation on this point, by having a look at other users’ issues with this, it is fair to assume that on Windows platforms, node-gyp
is only supported for Python
v2.7.X
(reference).
- download Python 2.7.X here: you can choose the bugfix release noted with an available link at the beginning.
- do a normal installation, and take note of the folder (preferably in a common folder where you will have all the python versions)
(5) node-gyp
Now it is the moment to correctly set up your node-gyp
configuration.
If you haven not installed it as yet:
npm install --global node-gyp
(5.1) Set the Python
version
According the documentation:
If the NODE_GYP_FORCE_PYTHON environment variable is set to the path of a Python executable, it will be used instead of any of the other configured or builtin Python search paths. If it’s not a compatible version, no further searching will be done.
- identify the full path to the
C:\full_path\Python2.7.X\python.exe
file (by full path we mean all: the folder path + the target filepython.exe
) - go to Control Panel -> System and open Advanced System Settings, tab Advanced
- at the bottom, click the button
Environmental Variables...
- a new panel pops up with two big sections: User Variables (only for the process owner), and System Variables (applicable to all the processes)
- on the System Variables, create a
New
entry - name it
NODE_GYP_FORCE_PYTHON
, and as value use the full path to the python.exe file version2.7.X
, and clickOK
and you are done
- for the variable to be available in the environment of your PowerShell terminal, you will need to close it and reopen a new terminal
- you have just fixed the
python
version to be used fornode-gyp
in your system
Alternatively you can use the command line below:
npm config set python /path/to/executable/python
(5.2) Set the Visual Studio Build Tools
version
This step should be fairly easy:
- identify the
year
of yourVisual Studio
edition (i.e. 2015, 2017, 2019) - use it in the year part of the command line below:
npm config set msvs_version year
For example, if you want it to use the MSBuild of 2019, use the command below:
npm config set msvs_version 2019
That must have done it.
(6) Testing node-gyp by creating a simple add-on in C++
References
- Mastering Node.js: Build robust and scalable real-time server-side web (by Sandro Pasquali & Kevin Faaborg, 2017, Packt Publishing): adapted example from here
- C++ Addons (official documentation)
- V8 Embed (explanation on how
V8
is embedded inC++
) - V8::FunctinonCallbackInfo Class Template reference for
Node.js
v12.0
Hands on work
In a test
folder, create test\hello_module
subfolder with the following empty files:
hello_module\hello.cc
(our sourceC++
native code)hello_module\binding.gyp
(instruction file fornode-gyp
)hello_module\index.js
(the wrapper)
In a terminal initialise the package by npm ini
. You can choose the offered default value by just pressing Enter
in all of them:
test\hello_module> npm ini
Now fill the files in with the contents specified below. Please, leave the index.js
for the end, since we will be compiling before using it.
The hello.cc
file content:
#include <node.h>
namespace hello_module {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void sayHello(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello World!"));
}
// the initialization function for hello_module
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "sayHello", sayHello);
}
// node.h C++ macro to export the initialization function
// (macros should not end by semicolon)
NODE_MODULE(NODE_GYP_MODULE_NAME, init)
}
- UPDATE (
2022-06-16
): at a suggestion of @Victor (see comments), to compile withNode.js 14
andMSVC 2017
at line 13, a call toToLocalChecked()
should be performed as well:
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello World!").ToLocalChecked())
The binding.gyp
file content:
{
"targets": [
{
"target_name": "hello",
"sources": [ "hello.cc" ]
}
]
}
You can leave the index.js
file for the end.
Now, let’s build the project:
test\hello_module> node-gyp configure
gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | win32 | x64
gyp info find Python using Python version 2.7.0 found at "C:\python\2.7.0\python.exe"
gyp info find VS using VS2019 (16.2.29123.88) found at:
gyp info find VS "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community"
# .. omited .. #
gyp info ok
The test\hello_module\build
folder should have been created with the basic project files to compile a C++
solution (this is what node-gyp
basically aims to: that you can use any C++
compiler without having to use the GUI
; in this case Visual Studio
).
Now, let’s build the addon:
test\hello_module> node-gyp build
At the end of both commands you should read gyp info ok
to know that everything was okay (you might not see it on a PowerShell terminal because of the blue background; if so, you can edit the Properties of the window and change Screen Background to black).
This command should have created the test\hello_module\build\Release
folder with the hello.node
file.
Notes:
- If everything went
ok
, you are done in verifying yournode-gyp
installation: it works!
- once you got this simple add-on to work, if you are still having issues with some package(s), that might be related to that package alone, or some of its dependencies, but your
node
ornode-gyp
configuration are okay
- if you encountered problems during the build, you might use the documentation to troubleshoot the source of the problem, or open a new post specifying which the errors you encountered are, and someone might be able to help
(7) Wrap and use the add-on in C++
This is an extra step. As you might have got here, why leaving it like this?
Now let’s write the wrapper hello_module\index.js
file:
const helloAddon = require('./build/Release/hello.node');
module.exports = helloAddon;
And in the test
folder, create the test\hello_world.js
file that uses our addon:
const {sayHello} = require('./hello_module');
console.log(sayHello())
And in the terminal:
test> node hello_world.js
You should see Hello World!
prompted on the screen.
Hope this helps anyone having issues to identify where exactly the configuration of node-gyp
failed to meet requirements.
node-gyp
— Node.js native addon build tool
node-gyp
is a cross-platform command-line tool written in Node.js for
compiling native addon modules for Node.js. It contains a vendored copy of the
gyp-next project that was previously used
by the Chromium team and extended to support the development of Node.js native
addons.
Note that node-gyp
is not used to build Node.js itself.
Multiple target versions of Node.js are supported (i.e. 0.8
, …, 4
, 5
, 6
,
etc.), regardless of what version of Node.js is actually installed on your system
(node-gyp
downloads the necessary development files or headers for the target version).
Features
- The same build commands work on any of the supported platforms
- Supports the targeting of different versions of Node.js
Installation
You can install node-gyp
using npm
:
Depending on your operating system, you will need to install:
On Unix
- A supported version of Python
make
- A proper C/C++ compiler toolchain, like GCC
On macOS
- A supported version of Python
Xcode Command Line Tools
which will installclang
,clang++
, andmake
.- Install the
Xcode Command Line Tools
standalone by runningxcode-select --install
. — OR — - Alternatively, if you already have the full Xcode installed, you can install the Command Line Tools under the menu
Xcode -> Open Developer Tool -> More Developer Tools...
.
- Install the
On Windows
Install the current version of Python from the
Microsoft Store.
Install tools and configuration manually:
- Install Visual C++ Build Environment: Visual Studio Build Tools
(using «Visual C++ build tools» if using a version older than VS2019, otherwise use «Desktop development with C++» workload) or Visual Studio Community
(using the «Desktop development with C++» workload)
If the above steps didn’t work for you, please visit Microsoft’s Node.js Guidelines for Windows for additional tips.
To target native ARM64 Node.js on Windows on ARM, add the components «Visual C++ compilers and libraries for ARM64» and «Visual C++ ATL for ARM64».
To use the native ARM64 C++ compiler on Windows on ARM, ensure that you have Visual Studio 2022 17.4 or later installed.
Configuring Python Dependency
node-gyp
requires that you have installed a supported version of Python.
If you have multiple versions of Python installed, you can identify which version
node-gyp
should use in one of the following ways:
- by setting the
--python
command-line option, e.g.:
node-gyp <command> --python /path/to/executable/python
- If
node-gyp
is called by way ofnpm
, and you have multiple versions of
Python installed, then you can set thenpm_config_python
environment variable
to the appropriate path:
export npm_config_python=/path/to/executable/python
Or on Windows:
py --list-paths # To see the installed Python versions set npm_config_python=C:\path\to\python.exe
-
If the
PYTHON
environment variable is set to the path of a Python executable,
then that version will be used if it is a supported version. -
If the
NODE_GYP_FORCE_PYTHON
environment variable is set to the path of a
Python executable, it will be used instead of any of the other configured or
built-in Python search paths. If it’s not a compatible version, no further
searching will be done.
Build for Third Party Node.js Runtimes
When building modules for third-party Node.js runtimes like Electron, which have
different build configurations from the official Node.js distribution, you
should use --dist-url
or --nodedir
flags to specify the headers of the
runtime to build for.
Also when --dist-url
or --nodedir
flags are passed, node-gyp will use the
config.gypi
shipped in the headers distribution to generate build
configurations, which is different from the default mode that would use the
process.config
object of the running Node.js instance.
Some old versions of Electron shipped malformed config.gypi
in their headers
distributions, and you might need to pass --force-process-config
to node-gyp
to work around configuration errors.
How to Use
To compile your native addon first go to its root directory:
The next step is to generate the appropriate project build files for the current
platform. Use configure
for that:
Auto-detection fails for Visual C++ Build Tools 2015, so --msvs_version=2015
needs to be added (not needed when run by npm as configured above):
node-gyp configure --msvs_version=2015
Note: The configure
step looks for a binding.gyp
file in the current
directory to process. See below for instructions on creating a binding.gyp
file.
Now you will have either a Makefile
(on Unix platforms) or a vcxproj
file
(on Windows) in the build/
directory. Next, invoke the build
command:
Now you have your compiled .node
bindings file! The compiled bindings end up
in build/Debug/
or build/Release/
, depending on the build mode. At this point,
you can require the .node
file with Node.js and run your tests!
Note: To create a Debug build of the bindings file, pass the --debug
(or
-d
) switch when running either the configure
, build
or rebuild
commands.
The binding.gyp
file
A binding.gyp
file describes the configuration to build your module, in a
JSON-like format. This file gets placed in the root of your package, alongside
package.json
.
A barebones gyp
file appropriate for building a Node.js addon could look like:
{ "targets": [ { "target_name": "binding", "sources": [ "src/binding.cc" ] } ] }
Further reading
The docs directory contains additional documentation on specific node-gyp topics that may be useful if you are experiencing problems installing or building addons using node-gyp.
Some additional resources for Node.js native addons and writing gyp
configuration files:
- «Going Native» a nodeschool.io tutorial
- «Hello World» node addon example
- gyp user documentation
- gyp input format reference
- «binding.gyp» files out in the wild wiki page
Commands
node-gyp
responds to the following commands:
Command | Description |
---|---|
help |
Shows the help dialog |
build |
Invokes make /msbuild.exe and builds the native addon |
clean |
Removes the build directory if it exists |
configure |
Generates project build files for the current platform |
rebuild |
Runs clean , configure and build all in a row |
install |
Installs Node.js header files for the given version |
list |
Lists the currently installed Node.js header versions |
remove |
Removes the Node.js header files for the given version |
Command Options
node-gyp
accepts the following command options:
Command | Description |
---|---|
-j n , --jobs n |
Run make in parallel. The value max will use all available CPU cores |
--target=v6.2.1 |
Node.js version to build for (default is process.version ) |
--silly , --loglevel=silly |
Log all progress to console |
--verbose , --loglevel=verbose |
Log most progress to console |
--silent , --loglevel=silent |
Don’t log anything to console |
debug , --debug |
Make Debug build (default is Release ) |
--release , --no-debug |
Make Release build |
-C $dir , --directory=$dir |
Run command in different directory |
--make=$make |
Override make command (e.g. gmake ) |
--thin=yes |
Enable thin static libraries |
--arch=$arch |
Set target architecture (e.g. ia32) |
--tarball=$path |
Get headers from a local tarball |
--devdir=$path |
SDK download directory (default is OS cache directory) |
--ensure |
Don’t reinstall headers if already present |
--dist-url=$url |
Download header tarball from custom URL |
--proxy=$url |
Set HTTP(S) proxy for downloading header tarball |
--noproxy=$urls |
Set urls to ignore proxies when downloading header tarball |
--cafile=$cafile |
Override default CA chain (to download tarball) |
--nodedir=$path |
Set the path to the node source code |
--python=$path |
Set path to the Python binary |
--msvs_version=$version |
Set Visual Studio version (Windows only) |
--solution=$solution |
Set Visual Studio Solution version (Windows only) |
--force-process-config |
Force using runtime’s process.config object to generate config.gypi file |
Configuration
Environment variables
Use the form npm_config_OPTION_NAME
for any of the command options listed
above (dashes in option names should be replaced by underscores).
For example, to set devdir
equal to /tmp/.gyp
, you would:
Run this on Unix:
export npm_config_devdir=/tmp/.gyp
Or this on Windows:
set npm_config_devdir=c:\temp\.gyp
npm
configuration for npm versions before v9
Use the form OPTION_NAME
for any of the command options listed above.
For example, to set devdir
equal to /tmp/.gyp
, you would run:
npm config set [--global] devdir /tmp/.gyp
Note: Configuration set via npm
will only be used when node-gyp
is run via npm
, not when node-gyp
is run directly.
License
node-gyp
is available under the MIT license. See the LICENSE
file for details.
Got to this post trying to get a correct set-up for node-gyp
, after upgrading Node.js
from v5.X
to v12.X
by overriding previous installation, and upgrading node-gyp
.
It seems fairly easy to miss some step when you already have a Visual Studio
environment and one or more versions of Python
installed.
I will try to synthesise here the steps that worked for me.
CONTEXT
Below the details as per configuration:
+-------+-----------------------------+-------------+-------------------------------------+ | | Component | Name | Version | +-------+-----------------------------+-------------+-------------------------------------+ | (1) | Platform | Windows 10 | NT 10.0.18362 | | (2) | Target run-time environment | Node.js | v12.16.1 | | (3) | Packet Manager | npm | v6.13.4 | | (4) | CLI Toolchain for compiling | node-gyp | v6.0.1 | | (4.a) | Compiler Language | Python | v2.7.0 | | (4.b) | Project Builder | MSBuild.exe | Microsoft (R) Build Engine for .NET | | | | | version 16.2.32702+c4012a063 | | | | | 16.200.19.32702 | +-------+-----------------------------+-------------+-------------------------------------+
Guideline
You might have already walked through some of the steps outlined here. If you incurred in some issues, you may be able to identify at which stage something went wrong by reviewing the steps in detail:
References
node-gyp
on GitHub: README.md (Generate Your Projects)- A Comprehensive Guide to Fixing Node-Gyp Issues on Windows (by Joe Bustamante; March 27, 2019)
- Setting up None.js on Windows 10 (by Ferenc Hámori; May 17, 2016)
- Using Python on Windows (official documentation)
(1) Node.js
This guideline assumes that git
is already installed in your machine (you will find the installer for Windows here anyways).
- Install
Node.js
: download the last LTS version for your platform (Windows Installer.msi
should work)
To verify it is correctly installed, in a test folder, add a file test.js
with this javascript
code: console.log("Node is installed!");
, and in a terminal run: node test.js
. You should be prompted with Node is installed!
.
(2) npm
- upgrade
npm
to the latest stable version using thenpm-windows-upgrade
package
Run as Administrator a PowerShell terminal:
PS C:\WINDOWS\system32> npm-windows-upgrade
You will be prompted to choose a version. The greatest available version among the options should be fine.
If you miss this package you might want to follow the instructions to install it by following the steps outlined in the GitHub repository, which basically are to type the following in a PowerShell console running as Administrator:
PS C:\WINDOWS\system32> Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
PS C:\WINDOWS\system32> npm install --global --production npm-windows-upgrade
PS C:\WINDOWS\system32> npm-windows-upgrade
(3) Visual Studio
If you have Visual Studio
already installed, you might skip this step, unless you wanted to also upgrade to the newest version.
In some posts, you might have read that you can achieve this step by simply using the following command line, after installing node-gyp
:
npm install --global --production windows-build-tools --vs2015
However, you could opt to achieve this by other means:
- you may have already an installation of
Visual Studio
and just want to configurenode-gyp
to use it - you may prefer to do a separated installation of
Visual Studio
and later on configurenode-gyp
to use it
This is really up to you. At a later stage, in this guideline, we will walk through the steps to configure the node-gyp
to use a specific Visual Studio
version.
(4) Python
In the installation guideline for node-gyp
(GitHub official repo) specifies which versions of Python
are currently compatible with the latest node-gyp
version on Unix and macOS. However it does not explain for Windows platforms (as at 1st of March 2020).
Although lack of documentation on this point, by having a look at other users’ issues with this, it is fair to assume that on Windows platforms, node-gyp
is only supported for Python
v2.7.X
(reference).
- download Python 2.7.X here: you can choose the bugfix release noted with an available link at the beginning.
- do a normal installation, and take note of the folder (preferably in a common folder where you will have all the python versions)
(5) node-gyp
Now it is the moment to correctly set up your node-gyp
configuration.
If you haven not installed it as yet:
npm install --global node-gyp
(5.1) Set the Python
version
According the documentation:
If the NODE_GYP_FORCE_PYTHON environment variable is set to the path of a Python executable, it will be used instead of any of the other configured or builtin Python search paths. If it’s not a compatible version, no further searching will be done.
- identify the full path to the
C:\full_path\Python2.7.X\python.exe
file (by full path we mean all: the folder path + the target filepython.exe
) - go to Control Panel -> System and open Advanced System Settings, tab Advanced
- at the bottom, click the button
Environmental Variables...
- a new panel pops up with two big sections: User Variables (only for the process owner), and System Variables (applicable to all the processes)
- on the System Variables, create a
New
entry - name it
NODE_GYP_FORCE_PYTHON
, and as value use the full path to the python.exe file version2.7.X
, and clickOK
and you are done
- for the variable to be available in the environment of your PowerShell terminal, you will need to close it and reopen a new terminal
- you have just fixed the
python
version to be used fornode-gyp
in your system
Alternatively you can use the command line below:
npm config set python /path/to/executable/python
(5.2) Set the Visual Studio Build Tools
version
This step should be fairly easy:
- identify the
year
of yourVisual Studio
edition (i.e. 2015, 2017, 2019) - use it in the year part of the command line below:
npm config set msvs_version year
For example, if you want it to use the MSBuild of 2019, use the command below:
npm config set msvs_version 2019
That must have done it.
(6) Testing node-gyp by creating a simple add-on in C++
References
- Mastering Node.js: Build robust and scalable real-time server-side web (by Sandro Pasquali & Kevin Faaborg, 2017, Packt Publishing): adapted example from here
- C++ Addons (official documentation)
- V8 Embed (explanation on how
V8
is embedded inC++
) - V8::FunctinonCallbackInfo Class Template reference for
Node.js
v12.0
Hands on work
In a test
folder, create test\hello_module
subfolder with the following empty files:
hello_module\hello.cc
(our sourceC++
native code)hello_module\binding.gyp
(instruction file fornode-gyp
)hello_module\index.js
(the wrapper)
In a terminal initialise the package by npm ini
. You can choose the offered default value by just pressing Enter
in all of them:
test\hello_module> npm ini
Now fill the files in with the contents specified below. Please, leave the index.js
for the end, since we will be compiling before using it.
The hello.cc
file content:
#include <node.h>
namespace hello_module {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void sayHello(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello World!"));
}
// the initialization function for hello_module
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "sayHello", sayHello);
}
// node.h C++ macro to export the initialization function
// (macros should not end by semicolon)
NODE_MODULE(NODE_GYP_MODULE_NAME, init)
}
- UPDATE (
2022-06-16
): at a suggestion of @Victor (see comments), to compile withNode.js 14
andMSVC 2017
at line 13, a call toToLocalChecked()
should be performed as well:
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "Hello World!").ToLocalChecked())
The binding.gyp
file content:
{
"targets": [
{
"target_name": "hello",
"sources": [ "hello.cc" ]
}
]
}
You can leave the index.js
file for the end.
Now, let’s build the project:
test\hello_module> node-gyp configure
gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | win32 | x64
gyp info find Python using Python version 2.7.0 found at "C:\python\2.7.0\python.exe"
gyp info find VS using VS2019 (16.2.29123.88) found at:
gyp info find VS "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community"
# .. omited .. #
gyp info ok
The test\hello_module\build
folder should have been created with the basic project files to compile a C++
solution (this is what node-gyp
basically aims to: that you can use any C++
compiler without having to use the GUI
; in this case Visual Studio
).
Now, let’s build the addon:
test\hello_module> node-gyp build
At the end of both commands you should read gyp info ok
to know that everything was okay (you might not see it on a PowerShell terminal because of the blue background; if so, you can edit the Properties of the window and change Screen Background to black).
This command should have created the test\hello_module\build\Release
folder with the hello.node
file.
Notes:
- If everything went
ok
, you are done in verifying yournode-gyp
installation: it works!
- once you got this simple add-on to work, if you are still having issues with some package(s), that might be related to that package alone, or some of its dependencies, but your
node
ornode-gyp
configuration are okay
- if you encountered problems during the build, you might use the documentation to troubleshoot the source of the problem, or open a new post specifying which the errors you encountered are, and someone might be able to help
(7) Wrap and use the add-on in C++
This is an extra step. As you might have got here, why leaving it like this?
Now let’s write the wrapper hello_module\index.js
file:
const helloAddon = require('./build/Release/hello.node');
module.exports = helloAddon;
And in the test
folder, create the test\hello_world.js
file that uses our addon:
const {sayHello} = require('./hello_module');
console.log(sayHello())
And in the terminal:
test> node hello_world.js
You should see Hello World!
prompted on the screen.
Hope this helps anyone having issues to identify where exactly the configuration of node-gyp
failed to meet requirements.
- Главная
- Front-end
- Установка node-gyp на Windows 8
Для работы некоторых модулей Node.js (например, MongoDB, Sails.js, Deployd) нужна компиляция нативного кода, написанного на C++. Это возможно с помощью модуля node-gyp, который, в свою очередь, собирает V8 используя питоновский gyp. Поэтому настроить node-gyp на Windows не просто, хотя на Ubuntu Linux у меня проблем с этим не возникало. В этом посте я поделюсь своим опытом исправления ошибок, которые возникали у меня при установке node-gyp на Windows, и опишу последовательность действий, которая позволила мне заставить сборку работать.
Для установки node-gyp необходимы Python и C++. Поэтому сначала ставим:
- Python 2.7
- Microsoft Visual Studio C++ 2013 for Windows Desktop Express
- и Windows 7 64-bit SDK, если у вас 64-битная система.
После этого надо запустить установку node-gyp глобально:
Если node-gyp установлен локально для проекта, то в некоторых случаях возможна ошибка Failed at install script ‘node-gyp rebuild’, например:
npm ERR! bufferutil@1.2.1 install: `node—gyp rebuild` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the bufferutil@1.2.1 install script ‘node-gyp rebuild’. npm ERR! Make sure you have the latest version of node.js and npm installed. npm ERR! If you do, this is most likely a problem with the bufferutil package, npm ERR! not with npm itself. |
Если у вас не установлен Python, или Node.js не может его найти, возникает ошибка Can’t find Python executable “python”, you can set the PYTHON env variable:
> node-gyp rebuild gyp info it worked if it ends with ok gyp info using node-gyp@3.3.0 gyp info using node@5.5.0 | win32 | x64 gyp ERR! configure error gyp ERR! stack Error: Can‘t find Python executable «python», you can set the PYTHON env variable. ... gyp ERR! node -v v5.5.0 gyp ERR! node-gyp -v v3.3.0 gyp ERR! not ok |
Это лечится установкой Python 2.7 (важно ставить именно эту версию, не знаю почему, но версия 3 не поддерживается!), и указанием в терминале пути к исполняемому файлу питона:
set PYTHON=C:\Users\Irina\AppData\Local\Programs\Python\Python27\python.exe |
Но указывать путь нужно будет каждый раз, когда вы запускаете node-gyp. Поэтому, если вы используете кастомный терминал (а я надеюсь, что вы это делаете), то лучше добавить эту команду в список команд, которые выполняются при запуске терминала.
Если не найден компилятор С++, то вы увидите ошибку `gyp` failed with exit code: 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
> node-gyp rebuild gyp info it worked if it ends with ok gyp info using node-gyp@3.3.0 gyp info using node@5.5.0 | win32 | x64 gyp http GET https://nodejs.org/download/release/v5.5.0/node-v5.5.0-headers.tar.gz gyp http 200 https://nodejs.org/download/release/v5.5.0/node-v5.5.0-headers.tar.gz gyp http GET https://nodejs.org/download/release/v5.5.0/SHASUMS256.txt gyp http GET https://nodejs.org/download/release/v5.5.0/win-x64/node.lib gyp http GET https://nodejs.org/download/release/v5.5.0/win-x86/node.lib gyp http 200 https://nodejs.org/download/release/v5.5.0/SHASUMS256.txt gyp http 200 https://nodejs.org/download/release/v5.5.0/win-x86/node.lib gyp http 200 https://nodejs.org/download/release/v5.5.0/win-x64/node.lib gyp info spawn C:\Users\Irina\AppData\Local\Programs\Python\Python27\python.exe gyp info spawn args [ ‘C:\\Users\\Irina\\AppData\\Roaming\\npm\\node_modules\\node-gyp\\gyp\\gyp_main.py’, ... gyp info spawn args ‘-Goutput_dir=.’ ] gyp: binding.gyp not found (cwd: C:\Users\Irina\Documents\project) while trying to load binding.gyp gyp ERR! configure error gyp ERR! stack Error: `gyp` failed with exit code: 1 gyp ERR! stack at ChildProcess.onCpExit (C:\Users\Irina\AppData\Roaming\npm\node_modules\node-gyp\lib\configure.js:305:16) gyp ERR! stack at emitTwo (events.js:100:13) gyp ERR! stack at ChildProcess.emit (events.js:185:7) gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12) gyp ERR! System Windows_NT 6.3.9600 gyp ERR! command «C:\\Program Files\\nodejs\\node.exe» «C:\\Users\\Irina\\AppData\\Roaming\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js» «rebuild» gyp ERR! cwd C:\Users\Irina\Documents\project gyp ERR! node -v v5.5.0 gyp ERR! node-gyp -v v3.3.0 gyp ERR! not ok |
Чтобы ее исправить, надо поставить Visual Studio C++ 2013 Express, ссылка на нее есть в начале поста. Имейте в виду, что это огромная среда, которая займет 6,5 гигабайт (!) места на диске (в такие моменты я особенно сильно ненавижу винду – компилятор gpp на Ubuntu в установленном виде занимает всего 17Мб). После этого надо перезагрузить компьютер, и запустить node-gyp rebuild.
© 2012-2023 Блог Ирины Соколовской
node-gyp
is a tool that enables the compilation of native add-on modules for Node in multiple platforms. It has widespread use and is included as a dependency in many NPM packages.
On most systems, this isn’t an issue, and installing node-gyp
with the rest of your packages works as expected. Unfortunately, this is not the case with Windows, as is evidenced by this thread from 2015. The Windows environment makes getting node-gyp
to work a less-than-stellar developer experience, full of multiple pitfalls and many ways for things to go wrong.
This guide is meant to help solve the issues that can arise when installing a package that requires node-gyp
.
1. Try running npm install
with the --no-optional
flag.
If you’re lucky, the dependency that requires node-gyp
will be optional, and you can skip the entire process required to get it working. Try running npm install –no-optional
to install only the required dependencies.
If you run this and still get the error, I have bad news: You’re in for a bit of a ride. As we begin our journey into getting node-gyp
up and running, here’s an important note for all of the steps that follow. Make sure that you’re always working in an elevated terminal (with administrator privileges) and that you restart your console whenever a download is complete.
2. Try downloading the windows-build-tools
package.
According to the node-gyp
documentation, this step should be the end-all-be-all solution to fixing node-gyp
problems. For most people, that’s true. NPM has a package called windows-build-tools
that should automatically install everything you need to get node-gyp
working, including the Microsoft build tools, compilers, Python, and everything else required to build native Node modules on Windows.
The good news is that installing this package should take care of all of the wiring up of these components. The bad news is that there are a lot of things included in it.
Depending on the version you download, it can hover between three and eight gigabytes (all to get some dependencies installed!). The install can take upwards of 30 minutes depending on your connection, so don’t despair if it seems like the install is hanging for a while.
You can download them by running this command: npm install --global --production windows-build-tools --vs2015
Important note
If you run this command without any additional flags, you’ll install the files associated with the latest version of Visual Studio, which is VS2017 at the time of writing. However, node-gyp
requires the v140
distributable, not the v150
(which comes with VS2017). This is why the --vs2015
flag is added to the end of the command, since that’s the last version of Visual Studio that came with the v140
package. You can see more notes about that near the bottom of the package’s website.
Hopefully, that’s all it will take for you to get everything installed. If you’ve still got issues, then you’re going to have to grab all of the required files manually.
3. Download the Visual Studio 2015 build tools manually.
Rather than installing the build tools through NPM, download them manually. You can find them on the Microsoft download page. Once they’re downloaded, just run the installer.
4. Tell Node to use the 2015 build tools.
Now that we have the build tools, we need to tell Node to use them. You’ll have to run this command: npm config set msvs_version 2015 –global
5. Make sure you have Python 2.7 installed.
Next up is to download Python 2.7. This is important–by default, you’ll install the newest version (3.x.x), but only 2.7 is compatible with node-gyp
. If you try to use a newer version of Python, you’ll get a syntax error due to print
being made into an actual function in Python 3.
If you have another version of Python already installed, that’s okay. They can coexist with each other. You can grab Python 2.7 at this link.
6. Set your Node config to use Python 2.7.
Now that you have Python 2.7, you’re going to have to set Node to use it by default. To do that, run this command: npm config set python python2.7
If you followed the last few steps, you should now have everything necessary to get node-gyp
working. Make sure you’ve restarted your terminal and are running it as an administrator, and try doing your install again. Hopefully, at this point, you can successfully install the dependencies you need. If not, we’re going to have to try one last thing.
7. Repeat Step 2 with the Visual Studio 2017 build tools.
I’ve personally had issues when I’ve tried to download the 2017 version of the build tools, even when trying to use newer versions of node-gyp
. If you look online, you’ll see lots of other people with the same problem, including some of the commenters on this StackOverflow question.
However, most of the documentation around node-gyp
and compiling native Node modules on Windows doesn’t specify to use the --vs2015
flag, and some even mention downloading the 2017 version. If you’re still having issues with getting node-gyp
to run, try repeating Step 2 while omitting the --vs2015
flag.
8. Try installing an older version of Node.
Still getting an installation error? Try installing an older version of Node. If you’re on an experimental version, try going back to the last stable release (and then make sure that you’re actually using that version when you try and do npm install
).
If that still doesn’t work, try going back to Node 8. You’ll find some issues online of people having issues with Node 10 that were resolved by downgrading to Node 8, and sometimes newer versions of Node don’t play nice with node-gyp
.
9. File an issue.
If you’re still having trouble getting node-gyp
to work, then your issue probably doesn’t fall into one of the more common problems. It’s worth doing some research online to see if that solves your problem. Otherwise, your best option is to file an issue on the GitHub page for node-gyp
and see what advice you can get there.
Other Resources
Much of this information can now be found on the GitHub readme for node-gyp, but it wasn’t always there. It only made an appearance after a few thousand posts from disgruntled Windows users who just wanted to install some dependencies. Even then, the information is missing some of the issues that arise with installing the wrong version of the build tools.
Another great resource is Microsoft’s guide on working with Node on Windows. It even has sections dedicated to compiling native Node modules and resolving basic node-gyp
problems.
Additionally, this question on StackOverflow contains useful answers and comments regarding this issue. Leave a note in the comments if you’ve found anything else helpful in solving node-gyp
issues!