How to Run NodeJS Server

On this page I will show you how to set-up and run a Node.js webserver to host a static web application on your local machine.

Node.js is lightweight and efficient. We can use it to deploy web-apps to our localhost or remote hosting. It is very easy to use and set-up

Download Node.js

Go to Node.js download page https://nodejs.org/download/ . There are 2 options for each OS – an installer and stand-alone executable. You can download the appropriate file for your OS.

Set up Node.js

Browse to the folder where you have installed (or extracted) node.js.

Create a folder named public_html  in the same folder as node executable – we will use this folder for our web projects

Create a new file webserver.js in the same folder as node executable with following content

var connect = require('connect');
var serveStatic = require('serve-static');

var app = connect();
app.use(serveStatic("public_html"));
app.listen(5100);

This simple JavaScript code implements a web server that serves HTTP requests for static HTML files hosted on http://localhost:5100 . It assumes that you create a public_html folder in the same folder where your node.exe (for Windows) or node executable file (OSX and Linux) resides

Now from within Node.js installation folder run this two commands (this will install the two modules required to run a static page)

npm install connect
npm install serve-static

Start the new server with

node webserver.js

Create an Example Page and Test the Server

Create a new file called test.html in public_html folder with following content:

<!DOCTYPE html>
<html>
<head>
	<title>Welocme page</title>
</head>
<body>
	Your simple Node.js server is up and running!
</body>
</html>

Now open your browser and type in http://localhost:5100/test.html

If everything went well you should see following in your browser

Node.js test page

Node.js test page

If you like this tutorial please share and comment.

Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+Digg thisPin on PinterestShare on RedditShare on StumbleUponPrint this pageEmail this to someone

Leave a Reply