Installing Node and NPM on Windows and macOS is straightforward because you can just use the provided installer:
- Download the required installer:
- Go to https://nodejs.org/en/
- Select the button to download the LTS build that is “Recommended for most users”.
- Install Node by double-clicking on the downloaded file and following the installation prompts.
Ubuntu 20.04
The easiest way to install the most recent LTS version of Node 12.x is to use the package manager to get it from the Ubuntu binary distributions repository. This can be done very by running the following two commands on your terminal:
curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
sudo apt-get install -y nodejs
Warning: Don’t install directly from the normal Ubuntu repositories because they contain very old versions of node.
Testing your Nodejs and NPM installation
The easiest way to test that node is installed is to run the “version” command in your terminal/command prompt and check that a version string is returned:
> node -v
v12.18.4
The Nodejs package manager NPM should also have been installed, and can be tested in the same way:
> npm -v
6.14.6
As a slightly more exciting test let’s create a very basic “pure node” server that prints out “Hello World” in the browser when you visit the correct URL in your browser:
- Copy the following text into a file named hellonode.js. This uses pure Node features (nothing from Express) and some ES6 syntax:
//Load HTTP module const http = require("http"); const hostname = '127.0.0.1'; const port = 3000; //Create HTTP server and listen on port 3000 for requests const server = http.createServer((req, res) => { //Set the response HTTP header with HTTP status and Content type res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World\n'); }); //listen for request on port 3000, and as a callback function have the port listened on logged server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
- The code imports the “http” module and uses it to create a server (
createServer()
) that listens for HTTP requests on port 3000. The script then prints a message to the console about what browser URL you can use to test the server. ThecreateServer()
function takes as an argument a callback function that will be invoked when an HTTP request is received — this returns a response with an HTTP status code of 200 ("OK") and the plain text "Hello World". - Note: Don’t worry if you don’t understand exactly what this code is doing yet! We’ll explain our code in greater detail once we start using Express!
- Start the server by navigating into the same directory as your
hellonode.js
file in your command prompt, and callingnode
along with the script name, like so:
>node hellonode.js Server running at http://127.0.0.1:3000/
- Navigate to the URL http://127.0.0.1:3000 . If everything is working, the browser should display the string “Hello World”.