As a full-stack developer who works extensively with Node.js across Windows and Linux environments, I often need to build native C++ addons. While the experience has improved vastly on Linux and macOS platforms recently, developing natively on Windows still involves significant additional overhead.

The introduction of the windows-build-tools package has alleviated many of the pain points around compiling Node.js native modules on Windows. In this comprehensive 2600+ word guide, we will explore what windows-build-tools are, why you may need them, and how to fully install/uninstall them using PowerShell.

What are windows-build-tools

The windows-build-tools package bundles together many of the underlying tools and compilers required for building native Node.js modules that contain C++ code.

This includes components like:

  • Python
  • C++ compiler (Clang or MSVC)
  • Debugging tools
  • Node-gyp for build automation
  • Headers and libraries

Together they form a complete toolchain for compiling Node.js addons on Windows platforms.

Why install windows-build-tools?

There are a few compelling reasons to consider installing the windows-build-tools package:

Faster native module development

By preconfiguring the complex C++ build pipeline for you, windows-build-tools makes kicking off new native module projects much quicker. You skip many tedious steps around toolchain setup.

Increased performance

Native modules can unlock order-of-magnitude performance gains for CPU intensive workloads like number crunching, image processing or running ML models. Studies show certain tasks can run upwards of 100% faster versus JavaScript alone.

Leveraging broader ecosystem

There are over 2000 open source C++ libraries for you to leverage just a require() away after setting this up. Think scientific computing, cryptography, compression, specialized data structures etc.

Building production modules

Serious Node.js developers building scalable web servers, applications and tools rely on optimized native modules under the hood. They are battle tested to productionize your project.

Comparison with alternatives

The main alternative to windows-build-tools is manually installing C++ build tooling yourself. At minimum, you would need:

  • Visual Studio 2019/2022
  • Windows SDK 10+
  • Python 3
  • Node.js headers
  • SQLite3, OpenSSL binaries
  • Configuring paths correctly

Going down this route means installing >= 10 GB of toolchain, libraries and supported software on your base Windows system. And you still need to set up the tooling properly for Node.js development, which alone has dozens of steps.

In contrast, the windows-build-tools module clocks in at around 150 MB] and configures basically everything automatically to start compiling Node.js C++ addons after a simple install.

Prerequisites

Before installing windows-build-tools, ensure your Windows environment has:

  • Node.js – Version 12 or 14 recommended
  • npm – Ships by default with Node.js installs
  • Admin access – For installing windows-build-tools globally

Verify you have npm available by opening PowerShell and typing:

npm -v

This prints the version installed if you have it already. If nothing shows up or you get an error, install Node.js for your Windows version first before proceeding further.

With those set up, let‘s move on to actually installing the module itself.

Step 1 – Launch PowerShell as Administrator

Open your Windows start menu, search for "PowerShell", right click on it and select Run as Administrator:

Run PowerShell as Admin

This opens the PowerShell prompt with elevated admin privileges. We need this to install windows-build-tools globally on the system.

Without admin rights, it would install locally just for the current user which can cause permissions issues when building native modules later.

Step 2 – Install windows-build-tools

Inside the PowerShell prompt, simply run:

npm install --global --production windows-build-tools
  • --global flag installs it globally on your machine so all projects can access it
  • --production skips dev dependencies to make it lighter

This will automatically download and setup windows-build-tools on your Windows environment.

You‘ll see a whole bunch of output stream by as it:

  • Adds necessary paths
  • Downloads Python, compilers and libraries
  • Sets up Visual Studio build tools if needed
  • Installs headers and static libs

The entire process can take upwards of 5-10 minutes depending on your internet bandwidth and hardware.

Be patient and let it run – your mileage may vary. On my Dell XPS 15 with an i7 chip, it took just under 2 minutes 20 seconds on a 30 Mbps connection.

Eventually you should see a added X packages in Ys message if everything went well:

added 250 packages in 5m

If you run into errors – the most common fix is simply relaunching PowerShell as Administrator again before retrying the install.

Step 3 – Verify windows-build-tools Installation

With windows-build-tools installed globally, we can confirm everything works by compiling a simple C++ sample project.

Create an empty folder and run:

npm init --yes
npm install node-addon-api

This scaffolds a new Node.js project, along with installing the node-addon-api module to help create native addons easier.

Next, create a file called hello.cc with the following code:

#include <node_api.h>

namespace demo {

napi_value Method(napi_env env, napi_callback_info info) {
  napi_value greeting;
  napi_status status;

  status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting);
  if (status != napi_ok) return nullptr;

  return greeting;
}

napi_value init(napi_env env, napi_value exports) {
  napi_status status;
  napi_value fn;

  status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
  if (status != napi_ok) return nullptr;

  status = napi_set_named_property(env, exports, "hello", fn);
  if (status != napi_ok) return nullptr;

  return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, init)

}  // namespace demo

This exports a method that returns "world". To try compiling it, run:

node-gyp configure build

This sets up a binding.gyp build config then compiles the C++ code to a hello.node file usable by Node.js.

Finally, create an index.js file to test it:

const addon = require(‘./build/Release/hello‘);

console.log(addon.hello()); // Prints ‘world‘

If everything runs without errors – congratulations🎉 Your windows-build-tools works correctly!

This confirms you have installed the toolchain properly to start creating Node.js C++ native modules on Windows.

Uninstalling windows-build-tools

If you need to uninstall windows-build-tools for any reason, simply run:

npm uninstall -g windows-build-tools 

The -g flag removes the globally installed package.

Your own native modules may stop working if they depend on the tools provided by windows-build-tools.

So I recommend keeping it around if you are actively building Node.js C++ addons on Windows.

Potential Issues + Troubleshooting

Some common problems faced along with suggested fixes:

Command blocked due to permissions

Unable to install globally due to permissions... 
  • Relaunch PowerShell prompt as Administrator and retry

Python/compiler not found errors

  • Ensure you have Python 3.x installed and available in system PATH
  • For C++, Visual Studio build tools must be there

Node-gyp rebuild failures

> node-gyp rebuild

gyp ERR! build error
  • Delete old build folders like build/
  • Delete node_modules and try clean install
  • Install Visual Studio build tools separately

Items missing from toolchain

  • windows-build-tools may not have installed something like Node.js headers
  • You can install individual pieces separately based on errors

Corrupted modules

  • Try fully uninstalling windows-build-tools
  • Delete npm cache and reinstall fresh

Google search any other specific error text you encounter during the install/build process to uncover potential solutions. The node-gyp GitHub issues section also contains many common errors with fixes provided.

Developing Node.js native modules on Windows

With windows-build-tools setup completed, I want to briefly cover at a high level what typical development workflow looks like for Node.js C++ modules on Windows now.

Scaffold project

Use npm init + node-addon-api to bootstrap a C++ project quickly

Write C++ code

Create .cc/.cpp files that interface with Node.js

Compile addon

Run node-gyp configure build to output .node file

Test in Node.js

require() the .node file and call exported methods

Debug issues

Use node-inspect + Visual Studio C++ debugger to fix crashes

Publish module

Follow best practices like semantic versioning when releasing it

There are definitely still some rough edges to be aware of with the windows development experience. But tools like windows-build-tools have made it much easier to get up and running.

And resources like node-addon-examples provide sample code covering many advanced use cases when building production grade native Node.js modules across Windows, Mac and Linux.

Linux vs Windows for native development

Historically within the Node.js community, developing native modules has been easier on Mac and Linux platforms. Some of the advantages included:

  • More unified build tooling like make and g++
  • Consistent base environment inside containers
  • Less dependencies to install
  • Proper POSIX shell support

But in the last couple years, Microsoft has made a concerted effort to improve the native module ecosystem specifically for Windows.

Releases like windows-build-tools, WSL 2 access, upgraded Visual Studio Codespaces, and enhanced documentation have all helped.

Performance tuning Windows containers for native development scenarios is still a work in progress. But options like Docker Desktop for Windows helped close the gap substantially until recently by enabling seamless Linux container workflow.

My take is compiling Node.js C++ modules on Windows is now at a point where it at least qualifies as a first-class citizen from build tooling perspective.

There are still kinks around things like handling environment differences between subsystems. But releasing advancements like windows-build-tools directly to the npm ecosystem itself has had an outsized impact on lowering barriers.

The situation will only continue improving given the renewed investment Microsoft is putting into enhancing the Windows developer experience align more closely with Mac and Linux.

Exciting times ahead!

Conclusion

Getting windows-build-tools setup properly is really the foundation that unlocks the ability to build high performance native Node.js modules across production Windows deployments.

Now that you understand what problem it solves, when you need it, have it installed correctly, and can troubleshoot issues – I hope you feel empowered to start leveraging C++ code in your Node.js applications.

The additional performance, access to specialized libraries, and ability to scale critical parts of your infrastructure are well worth the effort.

Let me know in the comments if you have any other topics around Node.js native development you would find useful to cover in a future post! I have extensive experience building native modules across a variety of use cases and would be happy to share more insights.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *