Getting started with web application development using a simple Node.js webserver

Get up and running with a Node.js webserver for your web application or working website by following these simple steps. I will share a script.js file which contains the script we are going to work in this little tutorial.

  1. First of all go to nodejs.org/download/‎ and install Node.js by downloading its executable setup.
    After you have installed make a new folder or select your existing folder where you want your web app to reside.
    You will need to install two Node.js modules for a nice experience. One is Nodemon and other of course well-known Node.js based implemented webserver Express, because we do not want to reinvent the wheel.
  2. Nodemon – Monitor for any changes in your node.js application and automatically restart the server – perfect for development.
  3. Express is a minimal and flexible node.js web application framework, providing a robust set of features for building single and multi-page, and hybrid web applications. We will be using its simple HTTP features.
  4. Open cmd (commond prompt) go into the directory of your work and write
    npm install nodemon -g //it will install the nodemon module.
    npm install express //it will install express web server module in this directory, we are not installing it
    for global use.
  5. Making web server:
    var express = require('express'),
    http = require('http'),
    app = express(),
    httpServer = http.createServer(app);
    express server is started using createServer method of htpp module that is built-in.
  6. Configuring web server:
    app.configure(function() {
    app.set('port',3000);
    app.use(express.static(__dirname + '/public'));
    });
    server will look the public directory as a http serving directory. If your script.js file will reside in the same directory as your index.html file, for example then change the directory to ‘/’ only.
  7. Starting the server:
    httpServer.listen(app.get('port'),function(){
    console.log("Express server listening on port %s.",httpServer.address().port);
    });

    Now go to the command prompt and write
    nodemon script.js
    it will run script.js as well start monitoring for any changes in the directory. Whenever you make any changes to any file just press Ctrl+S and the webserver will refresh these changes.

Now you have a simple webserver running you can continue your development of a web app.

Download Script.js file : Script.js

Advertisements
Getting started with web application development using a simple Node.js webserver