ndoe js primer

What is node.js?

Direct fromĀ Source:

it is a headless javascript engine.

it is literally the same JavaScript engine (named V8) that runs inside of Google Chrome, except that with Node.js, you can run JavaScript from the command line instead of in your browser.

what i have understood from reading is that its like the lego toy you give to kid…

you have the blocks and now you got to make building, vehicles etc…the choice is what you want to build….

why is it popular?

node.js uses only one language (JavaScript) left, right and centre….

isnt’t it cool to make great apps just knowing javascript alone….well thats the power of node.js

so lets cut the talk and walk the talk….

a basic hello node in nodejs


var http = require('http'); //import the http module

http.createServer(function(req, res) { //create an http server instance equivalent to triggering an httpd start on linux for LAMP
res.writeHead(200); //write header for OK status
res.end('hello node..let us start');
//res.end('Blank lines');
}).listen(8080);

save the file as http_test.js (name it what you want..doesnt matter)

open up a terminal and run the node instance

~[3]$>node /path/to/http_test.js

Fire up a browser and run

localhost:8080

now you should see the lines on the page:

hello node..let us start

Well thats the node.js up and running

a very important thing not documented everywhere (it must be dont know why it isnt):

try changing the lines to something else

var http = require('http'); //import the http module

http.createServer(function(req, res) { //create an http server instance equivalent to triggering an httpd start on linux for LAMP
res.writeHead(200); //write header for OK status
//res.end('hello node..let us start');
res.end('hello node i cant run as you expect you wont see me');
}).listen(8080);

try refreshing the browser page and you wont see your changes…instead you get a cached version of the file (older code ie. the older instance of node)

the reason is you need to restart the node instance with file name to re-parse the whole file…

you need to stop and re run the server to see your latest update.

ofcourse this is a pain in the ass to restart node instance everytime we make changes…but not to worry node.js has a great community and has already provided lots of solutions…

i prefer nodemon to automate the task of restarting node instance when you update your file or make changes to it

npm is node package manager your modules manager in node.js environment

1) Install nodemon. To install, from your terminal run:

npm install -g nodemon

2) Now, go to terminal, where you have the program. And, run

nodemon http_test.js

Now, everytime when you make changes to your app, just save your changes and it will get reflected.

Details :-

Nodemon is a utility that will monitor for any changes in your source and automatically restart your server