Before starting to explain how you start your first Node.js project for building a simple web server I will first explain you what Node.js is. To do so I just include a quote of the Node.js themself, because I don’t like to reinvent the wheel.
The next thing you should know is about the Node.js Package Manager (NPM). Using NPM you can benefit from the thousands of open source packages so you won’t have to build everything yourself.
I suppose you already have installed Node.js. Let’s start with a simple Hello World in Node.js by creating a file called hello-world.js and execute our script to show the result.
We can execute the script using following command. (On Windows open the Node.js command prompt) Navigate to your folder containing the just created hello-world.js file and execute the script using node.
Ok so we have just seen our very first Node.js application running. Before we start doing some more advanced stuff I first would like to install a package which will become very handy during development of our server, called nodemon. Nodemon will monitor our working directory and automatically restart our Node.js server when we make changes in our code. Because we want to reuse this package for all our future nodejs projects we will install this package globally using the -g command line parameter.
Now we can use nodemon to execute our scripts. Lets test it by starting our script using nodemon and then make a change to our script.
Now start another console so we can install our first package. We will install the package colors so we are able to give our console output some nice colors.
Then change our hello-world.js script to the following.
As you can see we require the colors script in our script so we can use it. When looking at your console you will also notice nodemon automatically restarted your script.
So now we have set our development environment and we can easily develop and test our script. Since I don’t like to reinvent the wheel we will use express.js to develop our webserver. First we need to install express.js using NPM.
Now we are able to use the express script in our hello-world.js script. Lets make some changes and see nodemon automatically restarting our script and launching our webserver.
Now our web server is listening on http://localhost:3000. We have configured the directory public to serve our static content. So lets add an html page to show an awesome “Hello Node.js express webserver” message. First create a folder public and then create a file called index.html in this folder.
Now open your web browser again and navigate to http://localhost:3000.
I hope this small guide was useful for you. Enjoy writing your own Node.js applications and share this article with your friends. Thanks for reading.
UPDATE: updated the console output to latest Node.js version and updated the express.js example to latest version.