What is NodeJS?
Node.js is an open-source, cross-platform, server-side JavaScript runtime environment built on Chrome’s V8 JavaScript engine originally authored by Ryan Dahl and released in 2009.
Does Node.js work on Windows?
Yes. Windows supports two different environments for developing apps with Node.js:
- Install a Node.js development environment on Windows
- Install a Node.js development environment on Windows Subsystem for Linux
For help determining which environment to use, check out Should I install on Windows or Windows Subsystem for Linux?
What can you do with NodeJS?
Node.js is primarily used for building fast and scalable web applications. It uses an event-driven, non-blocking I/O model, making it lightweight and efficient. It’s a great framework for data-intensive real-time applications that run across distributed devices. Here are a few examples of what you might create with Node.js.
- Single-page apps (SPAs): These are web apps that work inside a browser and don’t need to reload a page every time you use it to get new data. Some example SPAs include social networking apps, email or map apps, online text or drawing tools, etc.
- Real-time apps (RTAs): These are web apps that enable users to receive information as soon as it’s published by an author, rather than requiring that the user (or software) check a source periodically for updates. Some example RTAs include instant messaging apps or chat rooms, online multiplayer games that can be played in the browser, online collaboration docs, community storage, video conference apps, etc.
- Data streaming apps: These are apps (or services) that send data/content as it arrives (or is created) while keeping the connection open to continue downloading further data, content, or components as needed. Some examples include video- and audio-streaming apps.
- REST APIs: These are interfaces that provide data for someone else’s web app to interact with. For example, a Calendar API service could provide dates and times for a concert venue that could be used by someone else’s local events website.
- Server-side rendered apps (SSRs): These web apps can run on both the client (in your browser / the front-end) and the server (the back-end) allowing pages that are dynamic to display (generate HTML for) whatever content is known and quickly grab content that is not known as it’s available. These are often referred to as “isomorphic” or “universal” applications. SSRs utilize SPA methods in that they don’t need to reload every time you use it. SSRs, however, offer a few benefits that may or may not be important to you, like making content on your site appear in Google search results and providing a preview image when links to your app are shared on social media like Twitter or Facebook. The potential drawback being that they require a Node.js server constantly running. In terms of examples, a social networking app that supports events that users will want to appear in search results and social media may benefit from SSR, while an email app may be fine as an SPA. You can also run server-rendered no-SPA apps, which my be something like a WordPress blog. As you can see, things can get complicated, you just need to decide what’s important.
- Command line tools: These allow you to automate repetitive tasks and then distribute your tool across the vast Node.js ecosystem. An example of a command line tool is cURL, which stand for client URL and is used to download content from an internet URL. cURL is often used to install things like Node.js or, in our case, a Node.js version manager.
- Hardware programming: While not quite as popular as web apps, Node.js is growing in popularity for IoT uses, such as collecting data from sensors, beacons, transmitters, motors, or anything that generates large amounts of data. Node.js can enable data collection, analyzing that data, communicating back and forth between a device and server, and taking action based on the analysis. NPM contains more than 80 packages for Arduino controllers, raspberry pi, Intel IoT Edison, various sensors, and Bluetooth devices.
Next steps
- Should I install on Windows or Windows Subsystem for Linux (WSL)?
- Install NodeJS on Windows
- Install NodeJS on WSL
- Build JavaScript applications with Node.js learning path
Feedback
Submit and view feedback for
Introduction to Node.js
Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project!
Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows Node.js to be very performant.
A Node.js app runs in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.
When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.
This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.
Node.js has a unique advantage because millions of frontend developers that write JavaScript for the browser are now able to write the server-side code in addition to the client-side code without the need to learn a completely different language.
In Node.js the new ECMAScript standards can be used without problems, as you don’t have to wait for all your users to update their browsers — you are in charge of deciding which ECMAScript version to use by changing the Node.js version, and you can also enable specific experimental features by running Node.js with flags.
An Example Node.js Application
The most common example Hello World of Node.js is a web server:
const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World\n'); >); server.listen(port, hostname, () => console.log(`Server running at http://$hostname>:$port>/`); >);
To run this snippet, save it as a server.js file and run node server.js in your terminal.
This code first includes the Node.js http module.
Node.js has a fantastic standard library, including first-class support for networking.
The createServer() method of http creates a new HTTP server and returns it.
The server is set to listen on the specified port and host name. When the server is ready, the callback function is called, in this case informing us that the server is running.
Whenever a new request is received, the request event is called, providing two objects: a request (an http.IncomingMessage object) and a response (an http.ServerResponse object).
Those 2 objects are essential to handle the HTTP call.
The first provides the request details. In this simple example, this is not used, but you could access the request headers and request data.
The second is used to return data to the caller.
In this case with:
res.statusCode = 200;
we set the statusCode property to 200, to indicate a successful response.
We set the Content-Type header:
res.setHeader('Content-Type', 'text/plain');
and we close the response, adding the content as an argument to end() :
res.end('Hello World\n');
More Examples
See https://github.com/nodejs/examples for a list of Node.js examples that go beyond hello world.
Copyright OpenJS Foundation and Node.js contributors. All rights reserved. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.
Debugging Guide
This guide will help you get started debugging your Node.js apps and scripts.
Enable Inspector
When started with the —inspect switch, a Node.js process listens for a debugging client. By default, it will listen at host and port 127.0.0.1:9229. Each process is also assigned a unique UUID.
Inspector clients must know and specify host address, port, and UUID to connect. A full URL will look something like ws://127.0.0.1:9229/0f2c936f-b1cd-4ac9-aab3-f63b0f33d55e .
Node.js will also start listening for debugging messages if it receives a SIGUSR1 signal. ( SIGUSR1 is not available on Windows.) In Node.js 7 and earlier, this activates the legacy Debugger API. In Node.js 8 and later, it will activate the Inspector API.
Security Implications
Since the debugger has full access to the Node.js execution environment, a malicious actor able to connect to this port may be able to execute arbitrary code on behalf of the Node.js process. It is important to understand the security implications of exposing the debugger port on public and private networks.
Exposing the debug port publicly is unsafe
If the debugger is bound to a public IP address, or to 0.0.0.0, any clients that can reach your IP address will be able to connect to the debugger without any restriction and will be able to run arbitrary code.
By default node —inspect binds to 127.0.0.1. You explicitly need to provide a public IP address or 0.0.0.0, etc., if you intend to allow external connections to the debugger. Doing so may expose you to a potentially significant security threat. We suggest you ensure appropriate firewalls and access controls in place to prevent a security exposure.
See the section on ‘Enabling remote debugging scenarios’ on some advice on how to safely allow remote debugger clients to connect.
Local applications have full access to the inspector
Even if you bind the inspector port to 127.0.0.1 (the default), any applications running locally on your machine will have unrestricted access. This is by design to allow local debuggers to be able to attach conveniently.
Browsers, WebSockets and same-origin policy
Websites open in a web-browser can make WebSocket and HTTP requests under the browser security model. An initial HTTP connection is necessary to obtain a unique debugger session id. The same-origin-policy prevents websites from being able to make this HTTP connection. For additional security against DNS rebinding attacks, Node.js verifies that the ‘Host’ headers for the connection either specify an IP address or localhost precisely.
These security policies disallow connecting to a remote debug server by specifying the hostname. You can work-around this restriction by specifying either the IP address or by using ssh tunnels as described below.
Inspector Clients
A minimal CLI debugger is available with node inspect myscript.js . Several commercial and open source tools can also connect to the Node.js Inspector.
Chrome DevTools 55+, Microsoft Edge
- Option 1: Open chrome://inspect in a Chromium-based browser or edge://inspect in Edge. Click the Configure button and ensure your target host and port are listed.
- Option 2: Copy the devtoolsFrontendUrl from the output of /json/list (see above) or the —inspect hint text and paste into Chrome.
Note that the Node.js and the Chrome need to be run on the same platform.
Visual Studio Code 1.10+
- In the Debug panel, click the settings icon to open .vscode/launch.json . Select «Node.js» for initial setup.
Visual Studio 2017+
- Choose «Debug > Start Debugging» from the menu or hit F5.
- Detailed instructions.
JetBrains WebStorm and other JetBrains IDEs
- Create a new Node.js debug configuration and hit Debug. —inspect will be used by default for Node.js 7+. To disable uncheck js.debugger.node.use.inspect in the IDE Registry. To learn more about running and debugging Node.js in WebStorm and other JetBrains IDEs, check out WebStorm online help.
chrome-remote-interface
- Library to ease connections to Inspector Protocol endpoints.
Gitpod
- Start a Node.js debug configuration from the Debug view or hit F5 . Detailed instructions
Eclipse IDE with Eclipse Wild Web Developer extension
- From a .js file, choose «Debug As. > Node program», or
- Create a Debug Configuration to attach debugger to running Node.js application (already started with —inspect ).
Command-line options
The following table lists the impact of various runtime flags on debugging:
Flag | Meaning |
---|---|
—inspect | Enable inspector agent; Listen on default address and port (127.0.0.1:9229) |
—inspect=[host:port] | Enable inspector agent; Bind to address or hostname host (default: 127.0.0.1); Listen on port port (default: 9229) |
—inspect-brk | Enable inspector agent; Listen on default address and port (127.0.0.1:9229); Break before user code starts |
—inspect-brk=[host:port] | Enable inspector agent; Bind to address or hostname host (default: 127.0.0.1); Listen on port port (default: 9229); Break before user code starts |
node inspect script.js | Spawn child process to run user’s script under —inspect flag; and use main process to run CLI debugger. |
node inspect —port=xxxx script.js | Spawn child process to run user’s script under —inspect flag; and use main process to run CLI debugger. Listen on port port (default: 9229) |
Enabling remote debugging scenarios
We recommend that you never have the debugger listen on a public IP address. If you need to allow remote debugging connections we recommend the use of ssh tunnels instead. We provide the following example for illustrative purposes only. Please understand the security risk of allowing remote access to a privileged service before proceeding.
Let’s say you are running Node.js on a remote machine, remote.example.com, that you want to be able to debug. On that machine, you should start the node process with the inspector listening only to localhost (the default).
node --inspect server.js
Now, on your local machine from where you want to initiate a debug client connection, you can setup an ssh tunnel:
This starts a ssh tunnel session where a connection to port 9221 on your local machine will be forwarded to port 9229 on remote.example.com. You can now attach a debugger such as Chrome DevTools or Visual Studio Code to localhost:9221, which should be able to debug as if the Node.js application was running locally.
Legacy Debugger
The legacy debugger has been deprecated as of Node.js 7.7.0. Please use —inspect and Inspector instead.
When started with the —debug or —debug-brk switches in version 7 and earlier, Node.js listens for debugging commands defined by the discontinued V8 Debugging Protocol on a TCP port, by default 5858 . Any debugger client which speaks this protocol can connect to and debug the running process; a couple popular ones are listed below.
The V8 Debugging Protocol is no longer maintained or documented.
Built-in Debugger
Start node debug script_name.js to start your script under the builtin command-line debugger. Your script starts in another Node.js process started with the —debug-brk option, and the initial Node.js process runs the _debugger.js script and connects to your target.
node-inspector
Debug your Node.js app with Chrome DevTools by using an intermediary process which translates the Inspector Protocol used in Chromium to the V8 Debugger protocol used in Node.js.
Copyright OpenJS Foundation and Node.js contributors. All rights reserved. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.
Install NodeJS on Windows
If you are new to developing with Node.js and want to get up and running quickly so that you can learn, follow the steps below to install Node.js directly on Windows.
If you are using Node.js professionally, find performance speed and system call compatibility important, want to run Docker containers that leverage Linux workspaces and avoid having to maintain both Linux and Windows build scripts, or just prefer using a Bash command line, then install Node.js on Windows Subsystem for Linux (more specifically, WSL 2).
Install nvm-windows, node.js, and npm
Besides choosing whether to install on Windows or WSL, there are additional choices to make when installing Node.js. We recommend using a version manager as versions change very quickly. You will likely need to switch between multiple Node.js versions based on the needs of different projects you’re working on. Node Version Manager, more commonly called nvm, is the most popular way to install multiple versions of Node.js, but is only available for Mac/Linux and not supported on Windows. Instead, we recommend installing nvm-windows and then using it to install Node.js and Node Package Manager (npm). There are alternative version managers to consider as well covered in the next section.
It is always recommended to remove any existing installations of Node.js or npm from your operating system before installing a version manager as the different types of installation can lead to strange and confusing conflicts. This includes deleting any existing nodejs installation directories (e.g., «C:\Program Files\nodejs») that might remain. NVM’s generated symlink will not overwrite an existing (even empty) installation directory. For help with removing previous installations, see How to completely remove node.js from Windows.)
NVM is designed to be installed per-user, and invoked per-shell. It is not designed for shared developer boxes or build servers with multiple build agents. NVM works by using a symbolic link. Using nvm in shared scenarios creates a problem because that link points to a user’s app data folder — so if user x runs nvm use lts , the link will point node for the entire box to their app data folder. If user y runs node or npm, they will be directed to run files under x’s user account and in the case of npm -g , they will be modifying x’s files, which by default is not allowed. So nvm is only prescribed for one developer box. This goes for build servers too. If two build agents are on the same vm/box, they can compete and cause odd behavior in the builds.
- Follow the install instructions on the windows-nvm repository. We recommend using the installer, but if you have a more advanced understanding of your needs, you may want to consider the manual installation. The installer will point you to the releases page for the most recent version.
- Download the nvm-setup.zip file for the most recent release.
- Once downloaded, open the zip file, then open the nvm-setup.exe file.
- The Setup-NVM-for-Windows installation wizard will walk you through the setup steps, including choosing the directory where both nvm-windows and Node.js will be installed.
- Once the installation is complete. Open PowerShell (recommend opening with elevated Admin permissions) and try using windows-nvm to list which versions of Node are currently installed (should be none at this point): nvm ls
- Install the current release of Node.js (for testing the newest feature improvements, but more likely to have issues than the LTS version): nvm install latest
- Install the latest stable LTS release of Node.js (recommended) by first looking up what the current LTS version number is with: nvm list available , then installing the LTS version number with: nvm install (replacing with the number, ie: nvm install 12.14.0 ).
- List what versions of Node are installed: nvm ls . now you should see the two versions that you just installed listed.
- After installing the Node.js version numbers you need, select the version that you would like to use by entering: nvm use (replacing with the number, ie: nvm use 12.9.0 ).
Access Denied Issue in nvm-windows version 1.1.9, switching node version requires elevated Powershell (run as administrator). It is recommended to use version 1.1.7 to avoid this issue.
- To change the version of Node.js you would like to use for a project, create a new project directory mkdir NodeTest , and enter the directory cd NodeTest , then enter nvm use replacing with the version number you’d like to use (ie v10.16.3`).
- Verify which version of npm is installed with: npm —version , this version number will automatically change to whichever npm version is associated with your current version of Node.js.
Alternative version managers
While windows-nvm is currently the most popular version manager for node, there are alternatives to consider:
- nvs (Node Version Switcher) is a cross-platform nvm alternative with the ability to integrate with VS Code.
- Volta is a new version manager from the LinkedIn team that claims improved speed and cross-platform support.
To install Volta as your version manager (rather than windows-nvm), go to the Windows Installation section of their Getting Started guide, then download and run their Windows installer, following the setup instructions.
You must ensure that Developer Mode is enabled on your Windows machine before installing Volta.
To learn more about using Volta to install multiple versions of Node.js on Windows, see the Volta Docs.
Install Visual Studio Code
We recommend you install Visual Studio Code, as well as the Node.js Extension Pack, for developing with Node.js on Windows. Install them all or pick and choose which seem the most useful to you.
To install the Node.js extension pack:
- Open the Extensions window (Ctrl+Shift+X) in VS Code.
- In the search box at the top of the Extensions window, enter: «Node Extension Pack» (or the name of whatever extension you are looking for).
- Select Install. Once installed, your extension will appear in the «Enabled» folder of your Extensions window. You can disable, uninstall, or configure settings by selecting the gear icon next to the description of your new extension.
A few additional extensions you may want to consider include:
- Debugger for Chrome: Once you finish developing on the server side with Node.js, you’ll need to develop and test the client side. This extension integrates your VS Code editor with your Chrome browser debugging service, making things a bit more efficient.
- Keymaps from other editors: These extensions can help your environment feel right at home if you’re transitioning from another text editor (like Atom, Sublime, Vim, eMacs, Notepad++, etc).
- Settings Sync: Enables you to synchronize your VS Code settings across different installations using GitHub. If you work on different machines, this helps keep your environment consistent across them.
Alternative code editors
If you prefer to use a code editor or IDE other than Visual Studio Code, the following are also good options for your Node.js development environment:
Install Git
If you plan to collaborate with others, or host your project on an open-source site (like GitHub), VS Code supports version control with Git. The Source Control tab in VS Code tracks all of your changes and has common Git commands (add, commit, push, pull) built right into the UI. You first need to install Git to power the Source Control panel.
- Download and install Git for Windows from the git-scm website.
- An Install Wizard is included that will ask you a series of questions about settings for your Git installation. We recommend using all of the default settings, unless you have a specific reason for changing something.
- If you’ve never worked with Git before, GitHub Guides can help you get started.
- We recommend adding a .gitignore file to your Node projects. Here is GitHub’s default gitignore template for Node.js.
Use Windows Subsystem for Linux for production
Using Node.js directly on Windows is great for learning and experimenting with what you can do. Once you are ready to build production-ready web apps, which are typically deployed to a Linux-based server, we recommend using Windows Subsystem for Linux version 2 (WSL 2) for developing Node.js web apps. Many Node.js packages and frameworks are created with a *nix environment in mind and most Node.js apps are deployed on Linux, so developing on WSL ensures consistency between your development and production environments. To set up a WSL dev environment, see Set up your Node.js development environment with WSL 2.
If you are in the (somewhat rare) situation of needing to host a Node.js app on a Windows server, the most common scenario seems to be using a reverse proxy. There are two ways to do this: 1) using iisnode or directly. We do not maintain these resources and recommend using Linux servers to host your Node.js apps.