Starting a simple local webserver using NodeJS and Express

nodejs

Sometimes you just need a web server in your local computer but don’t want to bother installing a full fledged software like xampp, wamp, etc. to do it. Now-a-days almost everyone in the information technology industry have come across NodeJS. For those who don’t, NodeJS is an open source javascript based server framework. It is lightweight and has no-nonsense approach to manage things.

You should already have an installation of NodeJS to continue with this. If not, please refer to guides to get it installed in your machine.

Next you will need the ExpressJS framework for NodeJS to start the server. While you can use the inbuild http module of NodeJS to start the server, ExpressJS makes many things simpler in the long run.

To install ExpressJS, fire up the terminal, navigate to the folder where you want to setup the server, and type

npm install express

*Note – This is assuming you have the npm module installed.

Then create a file in the same folder named server.js (you can name it anything you want), and then paste the following code in there:

const express = require('express');
const app = express();
const port = 3000;

app.use('/', express.static(__dirname + '/'));

app.listen(port, function() {
    console.log("localhost running at port " + port);
});

Then in the terminal (assuming you are still in the same folder), type:

node server.js // the file name that you gave

If everything is fine till now, your console will display localhost running at port 3000. Now you can fire up your browser, type in localhost:3000 and see the results for yourself.

Bear in mind that if there is nothing to serve from the folder, it will show Cannot GET / .

Leave a Reply