Npm install global production windows build tools

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:

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.

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.

A well-prepared young man ready to start running. Cover photo by William Stitt on Unsplash.

Updated for Angular version 11.0.

Are you struggling with setting up an Angular development environment on Windows? Let us get you up and running in no time!

In November 2018, I attended ngHeroes as a mentor. It excited me to help students and people from other industries who wanted to learn web development with Angular. A lot of them wanted to start a new career. I was happy to notice more female attendance than I expected based on the gender gap in our industry.

I started my career as a software developer 7 years ago, but I did not forget what it was like to be new to programming. What I did forget was how much work we need to do to get up and running with the necessary tools.

The ngHeroes students had macOS, Linux, and Windows computers. We managed to get them up and running but hit some bumps along the way. In this article, I will focus on installing the tools and dependencies you need to develop Angular applications on a Windows machine. They are almost the same for other operating systems. Only the build tools step should differ.

If you run into trouble, comment on this article.

1. Node.js

Node.js

We use Node.js as a JavaScript runtime for many web development tools.

The first thing you need to install is Node.js. It is a JavaScript runtime that can run web servers, scripts, and console applications. A lot of web development tools use Node.js.

Go to the Node.js website. It offers you 2 installation packages based on your operating system and CPU architecture: LTS (Long-Term Support) and Current.

This is where it gets tricky. LTS is the right choice, but we might need an older LTS version. We need a version of Node.js LTS that the Angular CLI (Command-Line Interface) supports. Angular CLI is a development tool for Angular projects.

Figure 1. Node.js support in Angular CLI. Open in new tab.

For a new application, we can pick the newest version of Angular CLI. On jsDelivr, we can read the package details for the latest version of Angular CLI. At the time of writing, this is Angular CLI version 11.0. In the package details, we can also see the supported version of Node.js.

Towards the end of the JSON file, you will find a JSON object named "engines" and inside of that you will find the requirements for "node". For example, it says "node": ">= 10.13.0" for Angular CLI version 11.0. This means that we need at least version 10.13 of Node.js.

As seen in Figure 1, Angular CLI version 11.0.x has official support for Node.js versions 10 and 12.

We decided to use the newest Angular CLI. Let us go back to the Node.js website, download the installer for the latest LTS version supported by Angular CLI and run it with administrative privileges.

If you are asked whether to include Boxstarter or Chocolatey in the installation, do include it. More on that in a minute. Please give it time to finish installing. It might take a while and it could even require a reboot.

To verify that Node.js is installed, open a terminal (command prompt) and run node --version which displays the installed version of Node.js.

2. Windows Build Tools

PowerShell showing Windows Build Tools being installed

Installing Windows Build Tools with NPM CLI.

We decided to use the newest version of Angular CLI, but before we can install it, we need to take care of more dependencies.

To be specific, some compilation tools are used by the package node-gyp for pre and post install tasks for various packages such as Angular CLI.

For Windows, we need Python 2.7, Visual Studio Build Tools, and C++ Build Tools. Luckily, we can install them all as a single package using the NPM CLI.


If you previously installed Node.js with the Boxstarter or Chocolatey option included, you already have these dependencies. Skip to step 3.


Run the following command to install all the Windows-specific dependencies for Angular CLI. It uses the NPM (Node Package Manager) CLI to install from the NPM Public Registry. You installed NPM CLI with Node.js.

Make sure to use a terminal with administrator privileges. For example, right-click Command Prompt and choose “Run as administrator”.

NPM is like Composer (PHP), LuaRocks, Maven (Java), NuGet (.NET), pip (Python), and RubyGems, but for JavaScript.

npm install --global --production windows-build-tools

Enter fullscreen mode

Exit fullscreen mode

Wait until the installation finishes. It will say “All done!”


Installing the build tools should be the only step that differs from other operating systems than Windows. For example on Ubuntu and Debian you’ll run the command sudo apt install gcc g++ make python2.


3. Angular CLI

The Angular CLI logo

Angular CLI is a development tool for Angular applications.

Now we are ready to install Angular CLI. As before, we use NPM CLI to install it.

npm install --global @angular/cli

Enter fullscreen mode

Exit fullscreen mode

To verify that Angular CLI is installed, run the command ng --version which displays the installed version of Angular CLI and its dependencies.

4. Git

The Git logo

Git is a popular distributed version control system

We are almost ready to create a new Angular application project. Before we can do that, we need a version control system to be able to back up our source code to a server. It will also enable us to create checkpoints in time that we can return to if we get stuck.

I suggest Git which has excellent support in the code editor we are going to use. Git is also well-integrated with Angular CLI.

Go to the Git website. It will offer you an installation package based on your operating system.

5. Visual Studio Code

IntelliSense in an Angular component template

The Angular Language Service extension for Visual Studio Code adds IntelliSense to Angular templates.

We need a code editor to develop our Angular application. Visual Studio Code is a free code editor offered by Microsoft. It has excellent Angular and TypeScript support through extensions. Visual Studio Code supports Linux, macOS, and Windows.

Install and run the Stable Build from the Visual Studio Code website.

Make sure to install the Angular Language Service extension afterwards. It will add IntelliSense to your Angular templates.

Scaffold an Angular application

With all the tools installed, we can finally scaffold an Angular application. Open a command prompt and navigate to the directory that you want to create the project in.

Use the following Angular CLI command to create the necessary directory and files for a new Angular application. Replace my-app with the name of the application which will also be the name of the directory that Angular CLI creates.

By the way, don’t use a directory path that contains a space such as C:\Program Files (x86)\Angular. The Angular CLI development server has issues with serving static files that have a path containing spaces. Instead, choose a path such as C:\Projects.

ng new my-app

Enter fullscreen mode

Exit fullscreen mode

Angular CLI will ask you whether want routing. Most single-page applications (SPAs) will use routing. If this is your first time working with Angular, you can skip it by answering n (no).

You will also be prompted to select a stylesheet format. CSS is the native browser format. SCSS is the most popular stylesheet preprocessor. Pick the one you have experience with, or simply CSS if you are new to web development.

The installation will take a few minutes since it installs a lot of tools and library dependencies that are used by Angular and Angular CLI.

Time to start coding

The Angular.io home page cover

Time to start developing an Angular application. Try out the “Getting started with Angular” tutorial on Angular.io.

Now you have everything you need to start coding! Open the project directory with Visual Studio Code.

When developing your application, you will want to open a development web server. Angular CLI has prepared one for you which you can run with the following command from inside the root project directory.

npm start

Enter fullscreen mode

Exit fullscreen mode

which is an NPM script shortcut for

ng serve

Enter fullscreen mode

Exit fullscreen mode

Once the development server has finished compiling your application, you can open it in a browser by navigating to http://localhost:4200.

Every time you change a file and save it, your browser will refresh and show you the changes.

To stop a running development server, you have to press Ctrl+C, type y and hit Enter.

Angular CLI defined the start script in package.json. Try adding the --open flag to the script so that it becomes ng serve --open, then save package.json and run the server again with npm start.

Now, all you have to do is develop your application. If you lack ideas or confidence in your development skills, try the “Getting started with Angular” tutorial on Angular.io.

Additional learning resources

Read the guide “Version Control in Visual Studio Code” to learn about version control with Git in Visual Studio Code.

Angular.io has development guides for most of the Angular framework.

The Angular CLI can help you scaffold components, directives, Angular modules, pipes, and services. Find out more in the Angular CLI documentation.

Remember to back up your source code by committing and pushing your Git repository. GitHub, GitLab, and Bitbucket offer free private Git repositories for individuals.

Node.js is just JavaScript, right? So it should be really easy to run Node.js applications on Windows—just download and install Node, npm install, and go, right?

Well, for some applications, that’s true. But if you need to compile extensions, you’ll need a few more things. And, of course, with Node.js itself being constantly under development, you’ll want to lock down your development to a version your code can use. In this post, I’ll talk you through how we get our Windows command-line environments set up for the Node.js (actually, Electron) application my team is developing.

First Things First

No one wants to waste time hunting down downloads for a development environment. Instead, install Scoop first, and you’ll get a nice, clean way to add the packages you’ll need without a single web search.

Once you’ve got Scoop installed, it’s time to add some packages. For just Node.js, you’ll want the nodejs package, plus nvm for version management with NVM:

scoop install nodejs nvm

If your project uses Yarn, as ours does, you can grab that from Scoop, as well:

scoop install yarn

If you’re planning on checking out or committing code to GitHub, you’ll also want tools for that:

scoop install openssh git

To finish setting up Git with OpenSSH, note the post-install message that tells you to set up the GIT_SSH environment variable.

Finally, in case you want to quickly do things as an administrative user (which you may, later in this post!), I recommend you install Sudo, which knows how to elevate privileges inside a PowerShell session without spawning a brand new one:

scoop install sudo

Managing Node.js versions

The next thing you’ll want to do is make sure you’re on the right version of Node.js for your project. We’re using the latest LTS version for ours, which as of the time of this writing is 8.11.2. So we issue two NVM commands to install and use it:

nvm install 8.11.2
nvm use 8.11.2

If you’re familiar with NVM on Unix-like systems, you’ll find it works a little differently on Windows with Scoop. When you use a new Node.js version, it will update the binaries under scoop\apps\nvm instead of in $HOME/.nvm.

If you use a version and it doesn’t seem to be taking effect, check your PATH environment variable in the System Properties control panel (search for “environment”); it’s probably been re-ordered. Move the path containing scoop\apps\nvm to the top, and the NVM-selected version will now take precedence.

Compiling Extensions

We don’t have any of our own extensions that need building in our project, but some of our dependencies (namely, node-sass) do.

Extensions like these are built with node-gyp, and node-gyp needs two things: Python (2… wince) and a C compiler, neither of which are standard equipment on a Windows system. If you don’t have them and you need them to build extensions, you will see a long string of gyp ERR! messages when you install dependencies.

Thankfully, there’s a reasonably easy way to install them already configured for node-gyp: windows-build-tools.

After you’ve installed the Scoop nodejs package above, and assuming you installed Sudo, you can now run:

sudo npm install --global --production windows-build-tools

Note that we have observed these installers rebooting a system at least once, which effectively aborted the process. We fixed this in this one case by re-running the installer like so:

sudo npm uninstall --global windows-build-tools
sudo npm install --global --production windows-build-tools

The Moment of Truth

If all the installations worked, you should be ready to go. For our application, a

yarn install
yarn start

was all we needed—of course, you’ll want to start your application however you do normally.

In our case, our application started up and we were off and running. If you have found a more complex case, let me know how you solved it in the comments.

This page gives specific instructions on setting up Node-RED in a Microsoft Windows environment. The instructions are specific to Windows 10. They may also work for Windows 7 and Windows Server from 2008R2, but it is advisable not to use them due to lack of current support.

Note : Some of the following instructions mention the «command prompt». Where this is used, it refers to either the Windows cmd or PowerShell terminal shells. It is recommended to use PowerShell on all newer versions of Windows as this gives you access to commands and folder names that are closer to those of Linux/Mac.

Quick Start

1. Install Node.js

Download the latest LTS version of Node.js from the official Node.js home page. It will offer you the best version for your system.

Run the downloaded MSI file. Installing Node.js requires local administrator rights; if you are not a local
administrator, you will be prompted for an administrator password on install. Accept the defaults when installing. After installation completes, close any open command prompts and re-open to ensure new environment variables
are picked up.

Once installed, open a command prompt and run the following command to ensure Node.js and npm are installed correctly.

Using Powershell: node --version; npm --version

Using cmd: node --version && npm --version

You should receive back output that looks similar to:

2. Install Node-RED

Installing Node-RED as a global module adds the command node-red to your system path. Execute the following at the command prompt:

npm install -g --unsafe-perm node-red

3. Run Node-RED

Once installed, you are ready to run Node-RED.


Alternative Installations on Windows

In this section, we provide you with information on alternative ways to install Node.js, npm and the Windows Build Tools needed to install some Nodes for Node-RED on Windows.

Note : You should not use an administrative (a.k.a. «elevated») command prompt unless specifically instructed to. You will very likely need to be quite familiar with command prompts as you learn about Node-RED and Node.js and it will be worth while reading some of the Microsoft articles on PowerShell. the PowerShell Tutorial and PowerShell One-Liners sites may also be helpful.

Standard installations of Node.js on Windows require local administrator rights. Download the appropriate version from the official Node.js home page. It will offer you the best version. While you can use either 32 bit or 64 bit versions on 64 bit Windows, it is recommended to use the 64bit version of Node. If for some reason, you need a different installation, you can use the Downloads Page.

There are two potentially useful alternatives to installing Node.js with the MSI installer.

  1. Using the Chocolatey package manager

    Chocolatey is a package manager for Windows similar to APT or yum on Linux and brew on the Macintosh platforms. If you are already using Chocolatey, you may want to use this tool to install Node.js (e.g. using the nodejs-lts package). Note however, that many packages have uncertain management and that these packages may use different folder locations than those mentioned above.

  2. Using a Node version manager

    Using a Node.js version manager such as nvm-windows can be very helpful if you are doing Node.js development and need to test against different versions. Keep in mind that you will need to reinstall global packages and may need to re-install local packages when when you switch the version of Node you are using.

Note : Microsoft maintain a parallel version of Node that uses the Microsoft Chakra Core JavaScript engine instead of V8. This is not recommended for Node-RED as it has not been tested.

npm on Windows

When you install Node.js, you are also installing the npm package manager. You may see some instructions on the web that recommend installing later releases of npm than the one that comes with the Node.js release. This is not recommended as it is too easy to later end up with an incompatible version. Node.js releases are very regular and that is sufficient to keep npm updated.

Sharing Node-RED between Users

Node.js is installed into the Program Files folder as you would expect. However, if you install a global package like Node-RED using npm -g, it is installed into the $env:APPDATA\npm folder (%APPDATA%\npm using cmd) for the current user. This is less than helpful if you are installing on a PC with multiple user logins or on a server and installing using an admin login rather than the login of the user that will run Node applications like Node-RED.

Note : To see what a folder name like %APPDATA% translates to, you can simply type it into the address bar of the Windows File Explorer. Alternatively, in PowerShell, type the command cd $Env:APPDATA(cd %APPDATA% using cmd).

To fix this, either give permissions to the folder to other users and make sure that the folder is included in their path user environment variable.

Alternatively, change the global file location to somewhere accessible by other users. Make sure that you use the user that will be running Node-RED to make these changes. For example, to change the location to $env:ALLUSERSPROFILE\npmglobal using PowerShell:

mkdir $env:ALLUSERSPROFILE\npmglobal
npm config set prefix $env:ALLUSERSPROFILE\npmglobal

You will then want to change the npm cache folder as well:

mkdir $env:ALLUSERSPROFILE\npmglobal-cache
npm config set cache $env:ALLUSERSPROFILE\npmglobal-cache --global

If using the above changes, you can add the new prefix folder to the PATH System variable and remove the old folder from the user’s Path variable. To change the PATH Environment variable, type environment into the start menu or Cortana and choose Edit Environment Variables.

For each of the users running Node-RED, check that the above settings for the other users are correct.

Installing Node.js Windows Build Tools

Many Node.js modules used by Node-RED or installed nodes have binary components that will need compiling before they will work on Windows. To enable npm to compile binaries on the Windows platform, install the windows-build-tools module using the command prompt as an Administrator:

npm install --global --production windows-build-tools

If you wish to have the built-in Python v2.7 install exposed for use, use the command:

npm install --global --production --add-python-to-path windows-build-tools

Notes:

  • Not all Node.js modules will work under Windows, check the install output carefully for any errors.
  • During the install some errors may be reported by the node-gyp
    command. These are typically non-fatal errors and are related to optional dependencies
    that require a compiler in order to build them. Node-RED will work without these
    optional dependencies
    . If you get fatal errors, first check that you installed the windows-build-tools module and that you have closed and opened your command prompt window.

Running on Windows

Once installed, the simple way to run Node-RED is to use the node-red command in a command prompt:
If you have installed Node-RED as a global npm package, you can use the node-red command:

This will output the Node-RED log to the terminal. You must keep the terminal open in order to keep Node-RED running.

Note that running Node-RED will create a new folder in your %HOMEPATH% folder called .node-red. This is your userDir folder, think of it as the home folder for Node-RED configuration for the current user. You will often see this referred to as ~/.node-red in documentation. ~ is shorthand for the user home folder on Unix-like systems. You can use the same reference if using PowerShell as your command line as recommended. If you are using the older cmd shell, that won’t work.

You can now create your first flow.

Using PM2

If you are using Windows to develop Node-RED flows or nodes, you may find it helpful to use PM2 to run Node-RED. This can be configured to automatically restart when files change, always keep Node-RED running and manage log output.

Run Node-RED on Startup

If you want to use Windows as a production platform for Node-RED, you will want to have a Windows Task Scheduler job set up. To do so:

  1. Go to the start menu and type “task scheduler” and click on the result.
  2. Click on “Create Task…” in the right-hand menu. Follow the steps to create a new task.

Make sure that you use the user login that you’ve used to set up and do the initial run of Node-RED. You can use an “At startup” trigger to always run Node-RED at system startup. Use the Action “Start a program” with details set to C:\Users\<user>\AppData\Roaming\npm\node-red.cmd (replacing <user> with your actual user name).

You may wish to make sure that it only starts if the network is available. You may also wish to restart if the job fails. Perhaps restarting every minute but only 3 times — if it won’t start by then, the error is fatal and will need some other intervention. You can check for failures by looking in the event log. If you want to access to the logs when running this way, you should amend the node-red.cmd file to redirect std and error outputs to a file (creating an alternative startup file would be better so that it isn’t overwritten on updates).

От автора: наладить взаимодействие Angular Windows не всегда получается без проблем. Вы не можете настроить среду разработки? Позвольте нам помочь вам!

Недавно я был наставником ngHeroes. Мне очень понравилось помогать студентам и людям из других отраслей, которые хотели изучать веб-разработку на Angular. Многие из них хотели начать новую карьеру. Я был рад отметить, что посещаемость женщин больше, чем я ожидал, учитывая гендерный разрыв в нашей отрасли.

Я начал свою карьеру в качестве разработчика программного обеспечения 6 лет назад, но я не забыл, что значит быть новичком в программировании. То, что я действительно забыл — сколько работы нам нужно выполнить, чтобы начать работу с необходимыми инструментами.

У студентов ngHeroes были компьютеры на MacOS, Linux и Windows. Нам удалось их запустить, но в процессе возникло несколько сложных моментов. В этой статье я сосредоточусь на установке инструментов и зависимостей, необходимых для разработки приложений Angular на компьютере под управлением Windows. Они почти одинаковы для других платформ.

1. Node.js

Первое, что вам нужно установить, это Node.js. Это среда выполнения JavaScript, которая может запускать веб-серверы, скрипты и консольные приложения. Многие инструменты веб-разработки используют Node.js.

Перейдите на сайт Node.js. На нем предлагаются 2 установочных пакета, исходя из вашей операционной системы и архитектуры процессора: LTS (долгосрочная поддержка) и Текущий.

Вот где начинаются сложности. LTS — правильный выбор, но нам может понадобиться более старая версия LTS. Нам нужна LTS версия Node.js, которую поддерживает Angular CLI (интерфейс командной строки). Angular CLI — это инструмент разработки для проектов Angular.

Таблица 1. Поддержка Node.js в Angular CLI

Для нового приложения мы можем выбрать новейшую версию Angular CLI. На jsDelivr мы можем прочитать описание пакета для последней версии Angular CLI. На момент написания статьи это Angular CLI версии 7.0.5. В описании пакета мы также видим поддерживаемую версию Node.js.

В конце файла JSON вы найдете объект JSON с именем «engines», а внутри него требования для «node». Например, там будет указано «node»: «>= 8.9.0» для Angular CLI версии 7.0.5. Это означает, что нам нужна как минимум версия Node.js 8.9. Как видно из таблицы 1, Angular CLI версии 7.x также поддерживает Node.js 10.

Мы решили использовать новейший Angular CLI. Давайте вернемся на сайт Node.js, загрузим установщик последней версии LTS, поддерживаемой Angular CLI, и запустим его с правами администратора.

Если мастер установки спросит, включать ли Boxtstarter в установку, включите его. Подробнее об этом через минуту. Подождите, пока закончится установка. Это может занять некоторое время и даже может потребовать перезагрузки.
Чтобы убедиться, что Node.js установлен, откройте терминал (командную строку) и запустите node -v, чтобы отобразить установленную версию Node.js.

2. Инструменты сборки Windows

Установка инструментов сборки Windows с помощью NPM CLI

Мы решили использовать новейшую версию Angular CLI, но прежде чем мы сможем ее установить, нам нужно позаботиться о дополнительных зависимостях.

В частности, некоторые инструменты компиляции используются для задач пакетом node-gyp до и после установки для различных пакетов, таких как Angular CLI.

Для Windows нам нужны Python 2.7, инструменты сборки Visual Studio и инструменты сборки C++. К счастью, мы можем установить их все как один пакет, используя интерфейс командной строки NPM.

Если вы ранее установили Node.js с включенной опцией Boxstarter, у вас уже есть эти зависимости. Перейдите к шагу 3.

Выполните следующую команду, чтобы установить все специфичные для Windows зависимости для Angular CLI. Для установки из общедоступного реестра NPM используется интерфейс командной строки NPM (Node Package Manager). Вы установили интерфейс командной строки NPM с Node.js.

Обязательно используйте терминал с правами администратора. То есть, кликните правой кнопкой мыши на командной строке и выберите «Запуск от имени администратора». NPM похож на Composer (PHP), LuaRocks, Maven (Java), NuGet (.NET), pip (Python) и RubyGems, но для JavaScript.

npm install global production windowsbuildtools

Подождите, пока установка не закончится.

3. Angular CLI

Теперь мы готовы к установке Angular CLI. Как и прежде, мы используем NPM CLI для его установки.

npm install global @angular/cli

Чтобы убедиться, что Angular CLI установлен, выполните команду, ng —version, которая отображает установленную версию Angular CLI и ее зависимости.

4. Git

Мы почти готовы создать новый проект приложения Angular. Прежде чем мы сможем это сделать, нам нужна система контроля версий, чтобы иметь возможность выполнять резервное копирование исходного кода на сервере. Это также позволит нам своевременно создавать контрольные точки, к которым мы можем вернуться, если застрянем.

Я предлагаю Git, имеющий отличную поддержку в редакторе кода, который мы собираемся использовать. Git также хорошо интегрирован с Angular CLI. Перейдите на сайт Git. Вам будет предложен установочный пакет, исходя из вашей операционной системы.

5. Visual Studio Code

Расширение Angular Language Service для Visual Studio Code добавляет IntelliSense к шаблонам Angular

Нам нужен редактор кода для разработки приложения Angular. Visual Studio Code — это бесплатный редактор кода, предлагаемый Microsoft. Он имеет отличную поддержку Angular и TypeScript через расширения. Visual Studio Code поддерживает Linux, macOS и Windows.

Установите и запустите стабильную сборку с веб-сайта кода Visual Studio Code. Обязательно после этого установите расширение Angular Language Service. Это добавит IntelliSense к вашим шаблонам Angular.

Создание каркаса приложения Angular

Установив все инструменты, мы наконец можем приступить к созданию приложения Angular. Откройте командную строку и перейдите в каталог, в котором вы хотите создать проект.

Используйте следующую команду Angular CLI, чтобы создать необходимый каталог и файлы для нового приложения Angular. Замените my-app на имя приложения, которое также будет именем каталога, созданного Angular CLI.

Кстати, не используйте путь к каталогу, который содержит пробелы, такой как C:\Program Files (x86)\Angular. Сервер разработки Angular CLI имеет проблемы с обслуживанием статических файлов, путь которых содержит пробелы. Вместо этого выберите такой путь, как C:\Projects.

Angular CLI спросит вас, нужна ли вам маршрутизация. Большинство одностраничных приложений (SPA) используют маршрутизацию. Если вы впервые работаете с Angular, вы можете пропустить это.

Вам также будет предложено выбрать формат таблицы стилей. CSS является родным форматом браузера. SCSS — самый популярный препроцессор таблиц стилей. Выберите тот, с которым у вас есть опыт работы, или просто CSS, если вы новичок в веб-разработке.

Установка займет несколько минут, поскольку она включает установку множества инструментов и зависимостей библиотек, которые используются Angular и Angular CLI.

Пора приступать к кодированию

Теперь у вас есть все необходимое для кодирования! Откройте каталог проекта с помощью Visual Studio Code. При разработке приложения вам нужно будет открыть веб-сервер разработки. Angular CLI подготовил для вас тот, который вы можете запустить с помощью следующей команды из корневого каталога проекта.

это ярлык для скрипта NPM для

Как только сервер разработки завершит компиляцию приложения, вы можете открыть его в браузере, перейдя по адресу //localhost:4200.

Каждый раз, когда вы изменяете файл и сохраняете его, ваш браузер обновляется и отображает изменения. Чтобы остановить работающий сервер разработки, вам нужно нажать Ctrl+C, ввести Y и нажать Enter.

Angular CLI определил скрипт start в package.json. Попробуйте добавить в скрипт флаг —open, чтобы получилось ng serve —open, затем сохраните файл package.json и снова запустите сервер npm start.

Теперь все, что вам нужно сделать, это создать приложение. Если вам не хватает идей или уверенности в своих навыках разработки, попробуйте учебное пособие «Путь героев» на Angular.io.

Автор: Lars Gyrup Brink Nielsen

Источник: //medium.freecodecamp.org/

Редакция: Команда webformyself.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Какой звуковой драйвер лучше для windows 10
  • Asus wireless radio control windows 10
  • Какая технология автоматического восстановления не входит в состав операционной системы windows
  • Этот сайт не может обеспечить безопасное соединение windows 11
  • Таблица alt кодов windows