Tuesday, December 17, 2013

How to debug in node.js

1. Sample program:

~> vim hello-world.js

setTimeout(function(){
                console.log("world");
        }, 2000)

        console.log("hello");

        function foo() {
                debugger;
        return 1 + 2;
        }


2. Run the program as:
~> node debug hello-world.js

You get:

< debugger listening on port 5858
connecting... ok
break in hello-world.js:1
  1     setTimeout(function(){
  2         console.log("world");
  3     }, 2000)
debug> backtrace

#0 hello-world.js:1:64
debug>

How to check for concurrency in Node.js

1. Create a server.

~> vim web-server.js

  var http = require('http');


  var s = createServer(function(req,res) {


  res.writeHead("hello\n");

  setTimeout(function() {


  res.end("world");


  }, 2000);


  });


  s.listen(8000);


2. Run the server
 ~> node web-server.js

3. On another terminal make a request using curl:
~> curl http://localhost:8000/
hello
world

4. The hello and world have a gap of 2 seconds.

5. Run apache bench
ab -n 100 -c 100 http://localhost:8000/


All test happen in 2.0xx seconds.