Jade Tags ?

Any text at the beginning of a line—by default—is interpreted as an HTML tag. The main advantage of Jade is that this text renders both closing and opening tags for the HTML element, as well as the <>symbols. Therefore, we save many keystrokes as developers writing in Jade!

The text following a tag and a space (e.g.,tag ) is parsed as the inner HTML (i.e., content inside the element). For example, if we have the following Jade code:

Body
  div
    h1 Little Node.js
    p The only book most people will ever need.
  div
    footer &copy; Apress

The output of the template above will be:

<body>
  <div>
    <h1>Little Node.js</h1>
    <p>The only book most people will ever need.</p>
  </div>
  <div>
    <footer>&copy; Apress</footer>
  </div>
</body>
Posted in Jade Tagged with:

Middleware

we have used existing middleware (body-parser, cookie-parser, static, and connect-session, to name a few), and we’ve even written some of our own (when we check for the presence of &test=1 in the querystring, and our 404 handler).

But what is middleware, exactly?

Conceptually, middleware is a way to encapsulate functionality: specifically, functionality that operates on an HTTP request to your application. Practically, a middleware is simply a function that takes three arguments: a request object, a response object, and a “next” function.

Middleware is executed in what’s known as a pipeline. You can imagine a physical pipe, carrying water. The water gets pumped in at one end, and then there are gauges and valves before the water gets where it’s going. The important part about this analogy is that order matters: if you put a pressure gauge before a valve, it has a different effect than if you put the pressure gauge after the valve. Similarly, if you have a valve that injects something into the water, everything “downstream” from that valve will contain the added ingredient. In an Express app, you insert middleware into the pipeline by calling app.use.

Prior to Express 4.0, the pipeline was complicated by your having to link the router in explicitly. Depending on where you linked in the router, routes could be linked in out of order, making the pipeline sequence less clear when you mixed middleware and route handlers. In Express 4.0, middleware and route handlers are invoked in the order in which they were linked in, making it much clearer what the sequence is.It’s common practice to have the very last middleware in your pipeline be a “catch all” handler for any request that doesn’t match any other routes. This middleware usually returns a status code of 404 (Not Found).So how is a request “terminated” in the pipeline? That’s what the next function passed to each middleware does: if you don’t call next(), the request terminates with that middleware.

Learning how to think flexibly about middleware and route handlers is key to understanding how Express works. Here are the things you should keep in mind:

Route handlers (app.get, app.post, etc.—often referred to collectively as app.VERB) can be thought of as middleware that handle only a specific HTTP verb (GET, POST, etc.). Conversely, middleware can be thought of as a route handler that handles all HTTP verbs (this is essentially equivalent to app.all, which handles any HTTP verb; there are some minor differences with exotic verbs such as PURGE, but for the common verbs, the effect is the same).
Route handlers require a path as their first parameter. If you want that path to match any route, simply use /*. Middleware can also take a path as its first parameter, but it is optional (if it is omitted, it will match any path, as if you had specified /\*).

Route handlers and middleware take a callback function that takes two, three, or four parameters (technically, you could also have zero or one parameters, but there is no sensible use for these forms). If there are two or three parameters, the first two parameters are the request and response objects, and the third paramater is the next function. If there are four parameters, it becomes an error-handling middleware, and the first parameter becomes an error object, followed by the request, response, and next objects.

If you don’t call next(), the pipeline will be terminated, and no more route handlers or middleware will be processed. If you don’t call next(), you should send a response to the client (res.send, res.json, res.render, etc.); if you don’t, the client will hang and eventually time out.

If you do call next(), it’s generally inadvisable to send a response to the client. If you do, middleware or route handlers further down the pipeline will be executed, but any client responses they send will be ignored.
If you want to see this in action, let’s try some really simple middlewares:

app.use(function(req, res, next){
        console.log('processing request for "' + req.url + '"....');
        next();
});
 
app.use(function(req, res, next){
        console.log('terminating request');
        res.send('thanks for playing!');
        // note that we do NOT call next() here...this terminates the request
});
 
app.use(function(req, res, next){
        console.log('whoops, i\'ll never get called!');
});

Here we have three middlewares. The first one simply logs a message to the console before passing on the request to the next middleware in the pipeline by calling next(). Then the next middleware actually handles the request. Note that if we omitted the res.send here, no response would ever be returned to the client. Eventually the client would time out. The last middleware will never execute, because all requests are terminated in the prior middleware.

Now let’s consider a more complicated, complete example:

var app = require('express')();
 
app.use(function(req, res, next){
        console.log('\n\nALLWAYS');
        next();
});
 
app.get('/a', function(req, res){
        console.log('/a: route terminated');
        res.send('a');
});
app.get('/a', function(req, res){
        console.log('/a: never called');
});
app.get('/b', function(req, res, next){
        console.log('/b: route not terminated');
        next();
});
app.use(function(req, res, next){
        console.log('SOMETIMES');
        next();
});
app.get('/b', function(req, res, next){
        console.log('/b (part 2): error thrown' );
        throw new Error('b failed');
});
app.use('/b', function(err, req, res, next){
        console.log('/b error detected and passed on');
        next(err);
});
app.get('/c', function(err, req){
        console.log('/c: error thrown');
        throw new Error('c failed');
});
app.use('/c', function(err, req, res, next){
        console.log('/c: error deteccted but not passed on');
        next();
});
 
app.use(function(err, req, res, next){
        console.log('unhandled error detected: ' + err.message);
        res.send('500 - server error');
});
 
app.use(function(req, res){
        console.log('route not handled');
        res.send('404 - not found');
});
 
app.listen(3000, function(){
        console.log('listening on 3000');
});

Before trying this example, try to imagine what the result will be. What are the different routes? What will the client see? What will be printed on the console? If you can correctly answer all of those questions, then you’ve got the hang of routes in Express! Pay particular attention to the difference between a request to /band a request to /c; in both instances, there was an error, but one results in a 404 and the other results in a 500.

Note that middleware must be a function. Keep in mind that in JavaScript, it’s quite easy (and common) to return a function from a function. For example, you’ll note that express.static is a function, but we actually invoke it, so it must return another function. Consider:

app.use(express.static);        // this will NOT work as expected
console.log(express.static());  // will log "function", indicating
                                // that express.static is a function
                                // that itself returns a function
Posted in Express, Node.Js Tagged with: ,

Developing template engines for Express

To develop template engines for Express ,Use the app.engine(ext, callback) method to create your own template engine. ext refers to the file extension, callback is the template engine function which accepts the location of the file, the options object, and the callback function, as its parameters.

The following is an example of implementing a very simple template engine for rendering “.ntl” files.

var fs = require('fs'); // this engine requires the fs module
app.engine('ntl', function (filePath, options, callback) { // define the template engine
  fs.readFile(filePath, function (err, content) {
    if (err) return callback(new Error(err));
    // this is an extremely simple template engine
    var rendered = content.toString().replace('#title#', '<title>'+ options.title +'</title>')
    .replace('#message#', '<h1>'+ options.message +'</h1>');
    return callback(null, rendered);
  })
});
app.set('views', './views'); // specify the views directory
app.set('view engine', 'ntl'); // register the template engine

Your app will now be able to render “.ntl” files. Create a file named “index.ntl” in the views directory with the following content.

#title#
#message#

Then, create the following route in your app.

app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!'});
})

On making a request to the home page, “index.ntl” will be rendered as HTML.

More Info : Advanced Topics

Posted in Express, Node.Js Tagged with: ,

Response Object ?

The response object (which is normally passed to a callback, meaning you can name it whatever you want: it is common to name it res, resp, or response) starts its life as an instance of http.ServerResponse, a core Node object.The most useful properties and methods of the response object (all of these are added by Express):

res.status(code)
Sets the HTTP status code. Express defaults to 200 (OK), so you will have to use this method to return a status of 404 (Not Found) or 500 (Server Error), or any other status code you wish to use. For redirects (status codes 301, 302, 303, and 307), there is a method redirect, which is preferable.

res.set(name, value)
Sets a response header. This is not something you will normally be doing manually.

res.cookie(name, value, [options]), res.clearCookie(name, [options])
Sets or clears cookies that will be stored on the client. This requires some middleware support.

res.redirect([status], url)
Redirects the browser. The default redirect code is 302 (Found). In general, you should minimize redirection unless you are permanently moving a page, in which case you should use the code 301 (Moved Permanently).

res.send(body), res.send(status, body)
Sends a response to the client, with an optional status code. Express defaults to a content type of text/html, so if you want to change it to text/plain (for example), you’ll have to call res.set(‘Content-Type’, ‘text/plain\’) before calling res.send. If body is an object or an array, the response is sent as JSON instead (with the content type being set appropriately), though if you want to send JSON, I recommend doing so explicitly by calling res.json instead.

res.json(json), res.json(status, json)
Sends JSON to the client with an optional status code.

res.jsonp(json), res.jsonp(status, json)
Sends JSONP to the client with an optional status code.

res.type(type)
A convenience method to set the Content-Type header. It is essentially equivalent to res.set(‘Content-Type’, type), except that it will also attempt to map file extensions to an Internet media type if you provide a string without a slash in it. For example, res.type(‘txt’) will result in a Content-Type of text/plain. There are areas where this functionality could be useful (for example, automatically serving disparate multimedia files), but in general, you should avoid it in favor of explicitly setting the correct Internet media type.

res.format(object)
This method allows you to send different content depending on the Accept request header. This is of primary use in APIs. Here’s a very simple example:

res.format({'text/plain': 'hi there', 'text/html': '<b>hi there</b>'}).
res.attachment([filename]), res.download(path, [filename], [callback])

Both of these methods set a response header called Content-Disposition to attachment; this will prompt the browser to download the content instead of displaying it in a browser. You may specify filename as a hint to the browser. With res.download, you can specify the file to download, whereas res.attachment just sets the header; you still have to send content to the client.

res.sendFile(path, [options], [callback])
This method will read a file specified by path and send its contents to the client. There should be little need for this method; it’s easier to use the static middleware, and put files you want available to the client in the public directory. However, if you want to have a different resource served from the same URL depending on some condition, this method could come in handy.

res.links(links)
Sets the Links response header. This is a specialized header that has little use in most applications.

res.locals, res.render(view, [locals], callback)
res.locals is an object containing default context for rendering views. res.render will render a view using the configured templating engine (the localsparameter to res.render shouldn’t be confused with res.locals: it will override the context in res.locals, but context not overridden will still be available).
Note that res.render will default to a response code of 200; use res.status to specify a different response code.

Posted in Express, Node.Js

Request Object ?

The Request Object
The request object (which is normally passed to a callback, meaning you can name it whatever you want: it is common to name it req or request) starts its life as an instance of http.IncomingMessage, a core Node object. The most useful properties and methods of the request object (all of these methods are added by Express, except for req.headers and req.url, which originate in Node):

req.params
An array containing the named route parameters.

req.param(name)
Returns the named route parameter, or GET or POST parameters. I recommend avoiding this method.

req.query
An object containing querystring parameters (sometimes called GET parameters) as name/value pairs.

req.body
An object containing POST parameters. It is so named because POST parameters are passed in the body of the REQUEST, not in the URL like querystring parameters. To make req.body available, you’ll need middleware that can parse the body content type.

req.route
Information about the currently matched route. Primarily useful for route debugging.

req.cookies/req.signedCookies
Objects containing containing cookie values passed from the client.

req.headers
The request headers received from the client.

req.accepts([types])
A convenience method to determine whether the client accepts a given type or types (optional types can be a single MIME type, such asapplication/json, a comma-delimited list, or an array). This method is of primary interest to those writing public APIs; it is assumed that browsers will always accept HTML by default.

req.ip
The IP address of the client.

req.path
The request path (without protocol, host, port, or querystring).

req.host
A convenience method that returns the hostname reported by the client. This information can be spoofed and should not be used for security purposes.

req.xhr
A convenience property that returns true if the request originated from an AJAX call.

req.protocol
The protocol used in making this request (for our purposes, it will either be http or https).

req.secure
A convenience property that returns true if the connection is secure. Equivalent to req.protocol===’https’.

req.url/req.originalUrl
These properties return the path and querystring (they do not include protocol, host, or port). req.url can be rewritten for internal routing purposes, but req.originalUrl is designed to remain the original request and querystring.

req.acceptedLanguages
A convenience method that returns an array of the (human) languages the client prefers, in order. This information is parsed from the request header.

More Info : Express.js

Posted in Express, Node.Js Tagged with: ,

Cluster ?

A single instance of Node runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node processes to handle the load.

The cluster module allows you to easily create child processes that all share server ports,this gives your Node app access to the full power of your server.

var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log('I am the master,launching Workers!');
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  Object.keys(cluster.workers).forEach(function(id) {
    console.log("I am running with ID : "+cluster.workers[id].process.pid);
  });

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.process.pid + ' died');
  });
} else {
   console.log('I am a worker');
  // Workers can share any TCP connection
  // In this case its a HTTP server
  http.createServer(function(req, res) {
    res.writeHead(200);
    res.end("hello world\n");
  }).listen(8000);
}

If you observe the code, we are loading Cluster module in first line. Then we are counting how many cores do we have in our machine. Then in “if” condition , we are checking that if its Master process then create the copy of same process by number of core time.

If it is not the Master machine then basically run our normal Node program. So there would be one process which is master which in turn create processes number of core time.

In my case, i have Intel i3 consist of 4 core processor. If i run this code, i will get this output in terminal.
cmd

Posted in Node.Js Tagged with:

Return the response from ajax call ?

Return the response from ajax call ? : The A in AJAX stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow.

Synchronous : Imagine you make a phone call to a friend and ask him to look something up for you. Although it might take a while, you wait on the phone and stare into space, until your friend gives you the answer you needed.

The same is happening when you make a function call containing “normal” code:

function findItem() {
    var item;
    while(item_not_found) {
        // search
    }
    return item;
}
var item = findItem();
// do something with item
doSomethingElse();

Even though findItem might take a long time to execute, any code coming after var item = findItem(); has to wait until the function returns the result.

Asynchronous: You call your friend again for the same reason. But this time you tell him that you are in a hurry and he should call you back on your mobile phone. You hang up, leave the house and do whatever you planned to do. Once your friend calls you back, you are dealing with the information he gave to you.

That’s exactly what’s happening when you do an AJAX request.

findItem(function(item) {
    // do something with item
});
doSomethingElse();

Instead of waiting for the response, the execution continues immediately and the statement after the AJAX call is executed. To get the response eventually, you provide a function to be called once the response was received, a callback. Any statement coming after that call is executed before the callback is called.

There are basically two ways how to solve this:

Make the AJAX call synchronous (lets call it SJAX).
Restructure your code to work properly with callbacks.

1. Synchronous AJAX calls — DON’T DO IT

It is generally a bad idea to make AJAX calls synchronous. DON’T DO IT. I’m serious. I only mention it here for the sake of completeness. Why is it bad do you ask?

JavaScript runs in the UI thread of the browser and any long running process will lock the UI, making it unresponsive. Additionally, there is an upper limit on the execution time for JavaScript and the browser will ask the user whether to continue the execution or not. All of this is really bad user experience. The user won’t be able to tell whether everything is working fine or not. Furthermore the effect will be worse for users with a slow connection.

jQuery : If you use jQuery, you can set the async option to false. Note that this option is deprecated since jQuery 1.8. You can then either still use a success callback or access the responseText property of the jqXHR object:

function foo() {
    var jqXHR = $.ajax({
        //...
        async: false
    });
    return jqXHR.responseText;
}

If you use any other jQuery AJAX method, such as $.get, $.getJSON, etc., you have to change it to $.ajax (since you can only pass configuration parameters to $.ajax).

Heads up! It is not possible to make a synchronous JSONP request. JSONP by its very nature is always asynchronous (one more reason to not even consider this option).

Without jQuery : If you directly use a XMLHTTPRequest object, pass false as third argument to .open.

2. Restructure code

Let functions accept callbacks

The better approach is to organize your code properly around callbacks. In the example in the question, you can make foo accept a callback and use it as success callback. So this

var result = foo();
// code that depends on 'result'

becomes

foo(function(result) {
    // code that depends on 'result'
});

Here we pass a function as argument to foo. You can pass any function reference, for example:

function myCallback(result) {
    // code that depends on 'result'
}
foo(myCallback);

foo itself is defined as follows:

function foo(callback) {
    $.ajax({
        // ...
        success: callback
    });
}

callback will refer to the function we pass to foo when we call it and we simply pass it on to success. I.e. once the AJAX request is successful, $.ajax will call callback and pass the response to the callback (which can be referred to with result, since this is how we defined the callback).

You can also process the response before passing it to the callback:

function foo(callback) {
    $.ajax({
        // ...
        success: function(response) {
            // e.g. filter the response
            callback(filtered_response);
        }
    });
}

It’s easier to write code using callbacks than it seems. After all, JavaScript in the browser is heavily event driven (DOM events). Receiving the AJAX response is nothing else but an event.

Use deferred objects / promises

While directly passing callbacks works just fine, it can become inflexible in certain situations. Deferred objects / promises are a great way to deal with many callbacks and decouple your code.

Deferred objects are not unique to jQueryand there many independent implementations but I will only focus on jQuery in this answer.

Luckily for us, every AJAX method of jQuery already returns a promise which you can just return from your function and the calling code decides how to attach the callbacks:

function foo() {
    return $.ajax(...);
}

foo().done(function(result) {
    // code depending on result
}).fail(function() {
    // an error occurred
});

Describing all the advantages that deferred objects offer is beyond the scope of this answer, but if you write new code, you should seriously consider them. They provide a great abstraction and separation of your code.

Improving Bad Code : Deferreds can make it easy to transform broken asynchronous code into working code. For example suppose you had the following:

function checkPassword() {
    return $.ajax({
        url: '/password',
        data: {
            username: $('#username').val()
            password: $('#password').val()
        },
        type: 'POST',
        dataType: 'json'
    });
}

if (checkPassword()) {
    // Tell the user they're logged in
}

This code misunderstands the above asynchrony issues. Specifically, $.ajax() doesn’t freeze the code while it checks the ‘/password’ page on your server – it sends a request to the server and while it waits, immediately returns a jQuery Ajax Deferred object, which means your if statement is going to always get this Deferred object, treat that as true, and proceed as though the user is logged in. Not good.

But the fix is easy:

checkPassword()
.done(function(r) {
    if (r) {
        // Tell the user they're logged in
    } else {
        // Tell the user their password was bad
    }
})
.fail(function(x) {
    // Tell the user something bad happened
});

So now we’re still calling the ‘/password’ page on the server, but our code now properly handles the wait time for the server to respond. The $.ajax() call still returns immediately with a jQuery Ajax Deferred object, but we use it to attach event listeners to .done() and .fail(). In the .done() call, where the server responded with a normal response (HTTP 200), we check the object returned by the server. In this example the server is just returning true if the login was successful, false if not, so if (r) is checking for true/false.

In the .fail() handler we’re dealing with something going wrong – for example if the user lost their internet connection while they were typing in their username and password, or if your server went down.

Posted in Snippets

HOISTING in JavaScript

HOISTING in JavaScript :All JavaScript variables are hoist at the top of the scope (function) in which they are defined. To understand it consider the code snippet shows below,

var foo = "foo";
console.log(foo);

Above code will print foo in the console.Now let us go ahead and add a function as shown –

var foo = "foo";
console.log(foo);
(function () {
    console.log(foo);
}
)();

foo will be printed twice on the console. We saw that a variable defined outside a function scope or in global function scope can be used inside other functions. Let us go and modify the function as shown below,

var foo = "foo";
console.log(foo); // print foo
 (function () {
 
    console.log(foo); // print undefined
    var foo = "zoo";
}
)();

To be surprised now second console statement will print the value undefined.There are the reasons of that,
1) We have again declared foo inside the anonymous function.
2) JavaScript always hoist a variable declaration at the top of the scope. It only hoist the declaration not the initialization.

In actual, above anonymous function can be look like as. Declaration has been moved to the top of the function scope, whereas initialization is done at the place variable is declared.

(function(){
  var foo;
  console.log(foo); //Print undefined
  foo = 'zoo';
  console.log(foo); //Print zoo
}
)();

In above function, we are trying to access variable foo before it is initialized and that’s the reason we are getting undefined value printed. There are two types of scoping in the JavaScript,

1) Function scope.
2) Global scope.

Always a variable is hoisted at either the top of the function scope or global scope. When you use var to declare a variable inside a function, then that variable is inside that particular function scope. When you declare a variable without using var, it is always in the global scope.

More Info : Hoisting Simplified

Posted in Javascript

Express JS to Deliver HTML Files (1)

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 serve-static module to deliver the html file.

var express = require('express')
var serveStatic = require('serve-static')

var app = express()

app.use(serveStatic('public/', {'index': ['index.html', 'index.htm']}))
app.listen(3000);

Posted in Express, Node.Js

Convert String into MongoDB BsonDocument

If you have a long string in JSON format, and you want to convert it into a BSONDocument for insertion into a MongoDB database.You can simply do it by defining the query as

string json = "{ 'foo' : 'bar' }";  
BsonDocument document = BsonDocument.Parse(json);
Posted in MongoDB, Snippets