How to set up and run Node.JS for Beginners

Medhanie(Meda) Neguse
10 min readFeb 21, 2018

--

The following blog post is for those that are planning to start and setup their working environment for Node.js. In this blog, we will be covering the following four steps: first, installing Node.js, second adding your package.json file, third, how to setup your local host serve and finally I will show how you can run your first home (index.html) page using your local host. As I go through the steps, I will explain the steps and what each steps entails. Please note the focus of this tutorial is specifically for windows users.

I would like to mention to readers that this post is for complete beginners, so if you have previous experience in Node.js and have installed node in your local computer, this blog may not be appropriate for you.

Installing Node to your computer

Installing Node is very straight forward. All you have to do is go to the Node.js website here and download the recommended version for windows. If you are using Mac follow the instruction here.

Once the download is complete, run or install the downloaded file by double clicking on the file, or right click on the file and click install. After doing so, you will see the Node.js installation wizard. The default installation is always recommended so click next without changing anything and finish the installation. Once the installation is complete, you will see a folder called nodejs inside you program files.

Now open the folder and you will see a file with a name “node.exe”.

Run Node

You can run Node in two ways from your computer. The first one using the node.exe inside the nodejs folder in your program files. The second method is using the command line.

To run Node using node.exe file, double clicking on it or do right click on the file and hit open. This will open and run Node. You can test the node shell by typing a JavaScript code on it. I tested mine math operation and by calling the date method see the image below.

Now let’s try to run node from the command line. To use the command line go to your program by clicking on start and open the command Prompt. Once the command line opens type in “node” and hit enter on your keyboard. This will run node automatically. Please notice the change of the directory on the command line, it will change to a “>” sign. As we did earlier you can test if node is running by typing JavaScript codes as we did above.

Now that we know that Node is installed and runs as expected we have completed the first step successfully. Let us move to the next step of the tutorial which is creating the package.json file.

Creating package.jason file

Packages.json file is the best way to manage locally installed npm packages. These packages are the ones that your application is going to depend on. Moreover, your build will be easy to be copied by other developers if you wish to share them.

A package.json file must have a name of the application and the version of the application, without them our package won’t be installed. Also the name must be all lowercases and one word with no spaces, with the exception of dashes and underscores between words. The version on the other hand should follow the semantic versioning rules and it have to be in “x.x.x“ form. If you want to read about the semantic versioning in more detail, please click here.

For example here is apaskage.json file with the required fields name and a version specified.

In our application, we can create packages.json file using two methods. The first one is using the default process method and the second one is using the CLI questionnaire method.

To get the default package.json file, we run the “npm init” with the — yes or -y flag: by using this code we install our package.json file with the default setup.

npm init — yes

To create the package.json file using the CLI (Command Line Interface) questionnaire that allow us to supply our own values we use:

npm init

For this tutorial we will use “npm init”.

Let us create our own package.json file now, but before we do we have to create a folder for our application. I will create a folder called “myApp” inside my “C” drive. You can create the folder anywhere you want as long as you remember the file path. After creating the folder, open your command prompt and change the directory to the folder you created. To do that type “cd <Folder Path>” and hit enter. Ex: mine will be “cd C:/myApp” The path will change to the location of the folder you created.

Now type in the code specified above. I am going to use “npm init” to create the file.

After typing, hit enter and you will be prompt to add values to the package.json file. Please note that if you leave the values to the name, as well as leave the Package Name and version, the values in bracket will be added by default. I will give values to the name, main and author only. I will leave the version to its default which is 1.0.0.

name: mysimpleapp

version: leave as default which is 1.0.0

description: empty

main: app.js

scripts: empty

keywords: empty

author: empty

license: ISC

After filling the information you need, hit enter to confirm that it is okay to create the package.json file.

Now check inside the folder you created. You will see a package.json file that you created above. If you open the file you will see the information you specified in it. You can open the file using a test editor for code or you can use Notepad.

The purpose of package.json file is to manage the modules we use in our applications, they are also known as dependencies. Dependencies are modules that our application depends on. For example, if we want to use Express in our application we install Express from node package manager(npm). When we install Express, our package.json file will be updated and put express under dependencies. In the figure below application foo has three dependencies express, mocha and modules. These are modules the foo application depends on.

We are not going to install any modules for this tutorial, but you can try it to see for yourself. For more information on packages please click here.

Server

Now that we have created the package.json file, it is time to set up our server. We are going to use the app.js file we specify on the entry point during the package.json file creation. Inside the folder of our application create a new file called “app.js”.

Now open the file inside your text editor. I am using Sublime(https://www.sublimetext.com/) text editor, but you can use Notepad++, Notepad, or any other digital writing software to your liking. Once you open the app.js file copy the code below and paste it inside app.js file and save it. The code is from Node.js website you can find it here.

// this is how you import a module in Node. In the code bellow
// we are importing the 'http' module and storing it into the http //variable
const http = require('http');
// The code 127.0.0.1 is a loopback or it is called localhost
const hostname = '127.0.0.1';
// we are seting a port varable that holds 3000 as our port
const port = 3000;
//the code below will create a server by using the http object and //createServer method
//req == request
//res == response
const server = http.createServer((req, res) => {
//res,ststusCode is 200 meaning if everuthig is OKAY
res.statusCode = 200;
//the setHeader is here to tell the browser what kind of file we are //passing on, the content type we are passing a plain text
res.setHeader('Content-Type', 'text/plain');
//the code below is the one that will be printed on the browser. It //will print Hello World when the page loads
res.end('Hello World\n');
});
//the code below is here to listen on the server using the hostname //and port we specified above our port is 3000
// our hostname is 127.0.0.1 or localhost
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

If you are not sure what the code does, I have put a comment explaining what each line of code and method does.

Now we can open the command line and run the app.js file using node and it will create us a localhost server that we can use to run and test our application in the browser. To run the app.js file we created using the command line type in “node app” and hit enter. If you do everything correctly, you should see a message in the command line “Server running at http://127.0.0.1:3000/”. See image below.

To test if our application is running in the localhost, open any browser and type in “http://127.0.0.1:3000/” or “http://localhost:3000/”, you should see a text “Hello World” in your browser.

What we have now is just a server that says “Hello world”. In the feature when you build your application, this will be the place you see the changes. You can set your port to your desired port number Ex: 8000 and it will run in port 8000.

Now let see change the app.js file so it can run a template that we create. The template we are going to run is for our home or index page. To create our index template, let us create a index.html file inside our folder.

Now open the index.html on your text editor and use this html code below or create your own if you are familiar with html programming.

<!DOCTYPE html>
<html>
<head>
<title>My First App</title>
</head>
<body>
<h1>My Home Page.</h1>
</body>
</html>

In order to run the index.html file we need to do some changes in our app.js file, we have to tell our app to read the index.html file instead of printing “Hello World”. To do that we have to use the code below, so open your app.js file and replace it with the code below and save it.

const http = require('http');// we added the code below to read files that we created. fs stands // for file system. We import the file system to our application so // we can read the index.html file we created
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
// we are reading the index.html file we created by using the file // system object readFile method is used to read the index file
// we have two methods inside readFile mthod. error and html
fs.readFile('index.html', function(error, html){// we are checking if there is an error reading out index.html file // we are telling it to throw the error instead of crashing
if (error){
throw error;
} else {
// if there is no problem reading our index.html file we create our // server and write to our home page
const server = http.createServer((req, res) => {
res.statusCode = 200;
// we change the Content-type in here to texr/html - because we are // reading a html file (index.html)
res.setHeader('Content-Type', 'text/html');
//we are writing the html file to the browser
res.write(html);
res.end();
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
}
});

The only changes we made from the previous code is very minimum, but the setup is a little bit different since we are reading a file (index.html). I have commented on top of the code above to help you understand what we did.

If you run the server again it will read the index.html file we created and print “My Home Page” in the browser. If you did not see the change, you have to run the server again. In order to run the server again go to the command line, hold the control button and click “c“ this will exit and stop the server from running.

Now run it again, by typing “node app” again. This will refresh the server and will show you the changes we made. You can check the server in your browser “http://127.0.0.1:3000/” or http://localhost:3000/ to see the changes. You should see “My Home Page” see below.

Hopefully, you like my post and learned something from my tutorial. This post is just a basic explanation on how to setup your node environment and run a very simple server in Node.js using a code provided in node documentations. In my next blog post, I will try to give you something useful and a little bit more advanced material. If you need to learn more about the codes above please see the documentation in Node.js.

Thank you for reading.

--

--