Node JS to Deliver HTML Files

Node JS to Deliver HTML Files: The HTTP module is used to start up HTTP servers and respond to HTTP requests from users. The fs module is used to read the file system.Node js to deliver the html file while we have express js also for making it easy as well as fast.

var http = require('http');
var fs = require('fs');
  http.createServer(function(req, res){
    fs.readFile('test.html',function (err, data){
        res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
        res.write(data);
        res.end();
    });
}).listen(3000);

 console.log('Listen me at http://localhost:3000');

Another way to deliver the HTMl files using the serve-static module.

Serve-static

Posted in Express, Node.Js Tagged with:

Express JS to Deliver HTML Files

How to load and “display” a basic HTML file : There are many ways to simply send the html file using the node’s core api of using the readfile,but the easy way to do is using the Express Framework on the top of that.Here i am using expressjs to deliver the html file.

var express = require('express');
var app = express();
var path = require('path');

// viewed at http://localhost:8080
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(3000);
Posted in Express, Node.Js Tagged with: ,

Callbacks ?

What is Callbacks : You pass a function reference as a parameter to another function so that it can be executed at a later time

function f1(a){
}
function f2(b){
  var a=10;
   b(a);
}
f2 (f1);

Here i am passing f1 as a reference to f2. Then f2 is executing f1 inside its body.So f1 is the callback here because f2 has given some value to f1 as parameter which was f2’s local variable.

Posted in Javascript, Node.Js Tagged with: ,

Domain Module

A Node module called domain was introduced in Node 0.8.0 for handling errors. A domain module is like a flexible error handler for any and all errors that might be thrown within it. Using domains is the recommended method for handling uncaught errors in Node.

Note : The domain module is currently marked as Unstable, meaning, the API may change in the future.

What is a domain, exactly?
A domain is an EventEmitter object which, when “entered”, is accessible globally via process.domain and require(‘domain’).active. Multiple domains can exist in the domain stack, which is simply an array internally in Node holding all domains in the order they were created. Only one domain can be active on the process at a time, and is only active when it is “entered”. This is so that when Node.js is running code, it knows which domain should be notified about any unhandled errors that might occur.

Posted in Node.Js Tagged with:

Try-Catch to catch uncaught errors

The first thing that comes to the mind about handling uncaught errors is to use the try-catch on operations that are likely to throw a data error.

process.nextTick(function() {
    try {
      get_data();
    }
    catch(err) {
      console.log(err);
      res.send(500, 'Oops!');
    }
  });

Using try-catch can technically solve the uncaught error problem, but becomes unrealistic in complex situations. Following is an example to demonstrate this fact:

 process.nextTick(function() {
    try {
       process.nextTick(function() {
         set_data();
        });
          get_data();
       }
   catch(err) {
    console.log(err);
    res.send(500, 'Oops!');
    }
  });

Reference

Posted in Express, Node.Js Tagged with: ,

Error Handling in Node js

Error handling is a pain, and it’s easy to get by for a long time in Node.js without dealing with many errors correctly. But building robust Node.js(Node js) apps requires dealing properly with errors, and it’s not hard to learn how.
Node.js follows a callback pattern where an error object is the first argument and data is the second argument.
By default, when a runtime error occurs in an Express app, it will either be caught by the error handler defined in the router middleware or it will bring down the server.

    var http = require('http');
    var express = require('express');
    var app = express();
       app.get('/', function (req, res) {
        // Error will be caught
      get_data();
    });
var port = 3000;
app.listen(port);
console.log('Listening on port ' + port);

When you load http://localhost:3000/, you will get 500 Internal Server Error,but the server is still up and running, and users can still access the functional parts of the app.

Also there is another example of an uncaught error, which brings down the server.

 
    app.get('/', function (req, res) {
       // An async operation which causes an error
    process.nextTick(function() {
      get_data();
    });
  });

process.nextTick() is a low-level construct to execute instructions after the current set of instructions have been processed, making all the expressions within it asynchronous relative to the current set. You can read more about process.nextTick()
This time, when you load http://localhost:3000/, the app will crash instantly.

Posted in Express, Node.Js Tagged with: ,

Template engine Jade

Templates allow you to split your presentation information out from your program code,making it easier to arrange your project files and render out web pages with complicated structure. I am using jade template for this.
To install the Jade templating engine, use the NPM command :
npm install jade

   var express = require('express');
   var app = express();

     app.set('view engine', 'jade');
     app.set('view options', { layout: true });
     app.set('views', __dirname + '/views');

   app.get('/books/:name?', function(req, res, next) {
    var name = req.params.name;

    switch ( name ? name.toLowerCase() : '' ) {
     case 'node':
     case 'mongo':
     case 'javascript':
     res.render('books', {book: name});
      break;
    default:
    next();
   }
 });

    app.get('/books/*?', function(req, res){
     res.render('books', {book: null});
   });

    app.get('/?', function(req, res){
     res.render('index');
   });

var port = 3000;
app.listen(port);
console.log('Listening on port ' + port);

— views, the directory where the template files are located. Eg: app.set(‘views’, ‘./views’)
— view engine, the template engine to use. Eg: app.set(‘view engine’, ‘jade’)

The render command in Express takes care of loading any of the required template modules.

More Info : Templating Engine Jade.
Advanced

Posted in Express, Node.Js Tagged with: ,

Express Application

A simple and small practical server built using Express. To begin, the variable app is initialized by calling the express() function from the express library. The require command instructs Node to import the library express and assign it to a local variable (also called express).

   var express = require('express');
   var app = express();
     app.get('/books/:name?', function(req, res, next) {
        var name = req.params.name;
        switch ( name ? name.toLowerCase() : '' ) {
         case 'node':
         case 'mongo':
         case 'javascript':
         res.send(name + ' is my favorite book.');
         break;
     default:
     next();
   }
});
    app.get('/books/*?', function(req, res){
      res.send('no books listed');
   });

   app.get('/?', function(req, res){
     res.send('hello world');
   });

   var port = 3000;
   app.listen(port);
   console.log('Listening on port ' + port);

The three routes which i defined are :
/books/[name]
Expecting the name of one of the books as input
/books/
A fallback from the previous route, in case the name provided was not found
/
A default route used to access the application’s home page.

In the first route, Express is instructed to compare the name of the book provided and print a message if the name is ‘node’, ‘mongo’, or ‘javascript’. In the next route, Express displays a message stating simply that no books are listed, and in the third route, a default ‘hello world’ message is displayed.

The parameter next refers to a function. The next command instructs Express to try processing the next route matching the current request. In this example, entering the URL /books/ is intercepted by the first defined route (/books/:name?) rather than the second (/books). Since there was no name supplied, the logic will fall through to the default case in the switch statement at which point the next() function will be called. The next route (/books) contains the expected response.The question mark after the :name parameter indicates that the name is an optional input—this route will load even if no name is provided.

Posted in Express, Node.Js Tagged with: ,

Constructor Function 2 ?

How Does That Work?

Here’s what happens when a function is called with the “new” keyword :-
A call to “new Foo()” creates a new object instance, said to be of type “Foo”.The object instance is assigned a prototype of “Foo.prototype”.The “Foo” function is then invoked with the new object instance assigned to “this” in that function invocation.

The “Foo” object instance is returned from the function call.Since the value of “this” is a new object of a “Foo” type, in this example, the assignment of “this.bar” adds a “bar” attribute to the Foo instance. Logging “this” from the constructor function will log the object in it’s current state (with it’s current attributes and methods). When the constructor function exits, the object instance is assigned to the “f” variable. The “f” variable, pointing to the object instance, then has the “bar” attribute available, which is then logged to the console.

You should know that the “new” keyword changes the behavior of a function. It turns that function in to a constructor function. The value of “this” inside of the constructor function is a new instance of that object type, where the “type” is defined by the constructor function, itself.

The value of “this” is once again determined by the invocation pattern of the function and not by the function definition. Calling “new Foo.Bar.Baz()” will assign an instance of a “Baz” type to “this” inside of the “Baz” function.

Posted in Javascript Tagged with:

Constructor Function ?

A Constructor Function :
Consider the following function and call to the function:

  function Foo(){
    this.bar = "baz";
    console.log(this);
  }
  
  var f = new Foo();
  console.log(f.bar);

In this example, the “Foo” function is being used as a constructor function – a function that is designed to create object instances. Note that there is nothing in the JavaScript language that says this is a constructor function, nor is there anything that says a function must be set up in a certain way in order to be a constructor function.There are a few subtle hints in the patterns of JavaScript usage that tell us this is a constructor function.
1) The first hint is that the function name is capitalized. 2)The second is the assignment of “this.bar” in the function. 3)The final hint is the use of the “new” keyword.

From the above code, You will see two things in the console. The first of which will be the logging of “this” from the function itself. That call will produce an object in the console, which contains an attribute of “bar” assigned to the value of “baz”. The second thing you will see is the string “baz”, logged from the “f.bar” attribute, after the object is instantiated.

But … Why?

When a function is used as a constructor (and keep in mind that any function can be used as a constructor – though the results are not guaranteed if the function was not designed for this), the value of “this” within that function becomes something new and unique. It becomes an object instance, of the “type” that the function represents.

In the above example, then, the value of “this” is a new instance of a “Foo” object. When the function exits, the value of “this” is returned automatically – you don’t need to return anything manually.

Posted in Javascript Tagged with: