You can download the NodeJS installer from here.
Creating an HTTP server which responds to client query is very easy to build with node.js.
Just write below code in a file and save as server.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Node.js\n');
}).listen(80, "127.0.0.1");
console.log('Server running at http://127.0.0.1:80/');
To run the server, execute a file with the node program from the command line.
C:\> node server.js
So whenever you access http://127.0.0.1 from the browser and through any HTTP Client, it will respond with “Hello Node”.
Express.js
Express.js works as middleware and provides light-weight application framework to help to organize server side web applications.
Express.js is a very popular module which provides various feature like robust routing, Dynamic view helpers, Focus on high performance, view rendering, session support and High test coverage.
The same code written earlier can be written as below in express.js:
var express = require('express');
var app = express();app.get('/', function(req, res){ res.send('hello world');});
app.listen(80);
Let’s Create One Simple Application with Node.js
Let’s see an example of User Management, which allows creating, updating, removing or to get the user information from the database. These are the basic operations, which are used by most of the applications in which there are involvement of the users.
Note: In this example we are using MongoDB as a Database. So make sure that MongoDB process is running while executing this code.
Check below the URL endpoint which we are creating for achieving this:
Method |
URL |
Action |
GET |
/user |
Retrieves all users. |
GET |
/user/[id] |
Retrieve user specified by id. |
POST |
/user |
Add a new user. |
PUT |
/user/[id] |
Update user specified by id. |
DELETE |
/user/[id] |
Delete user specified by id. |
For creating this functionality code is divided into three files:
Filename |
Purpose |
App.js |
We will define all the routes. |
UserController.js |
Defines all the Business Logic to perform user related operations |
Model.js |
Defines the Database schema for User Entity |
App.JS
var express = require('express');
var userController = require('./usercontroller.js');
var mongoose = require(' mongoose');
// Initializing express Object
var app = express();
app.configure(function () {
app.use(express.logger('dev'));
app.use(express.bodyParser());
});
// Connecting to Database
mongoose.connect(mongodb://localhost/myDb);
// Start writing Routes here.
app.get('/user', userController.getAllUsers);
app.get('/user/:id', userController.getUserById);
app.post('/user', userController.addUser);
app.put('/user/:id', userController.updateUser);
app.delete('/user/:id', userController.deleteUserById);
// Starts Listening on port 9000
app.listen(9000);
console.log ('Server listening on port : 9000');