Starting with Node.js
Node.js is a server side open source, crossplatform built for easily building fast and scalable realtime web applications. It uses event driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.provides a rich library of various JavaScript modules which simplifies the development of web applications using Node.js to a great extent.
Node is not a webserver. If you want it to be a HTTP server you have to write an HTTP server (with the help of its built-in libraries). Node.js is just another way to execute code as it is just a JavaScript runtime platform with powerful set of libraries(modules) for doing real things.
Let's start with simple Node.js works,
Reading a file from node.js
Assume that you have a file named "myfile.txt" with some context written.
To read the file in the log,
// Load the fs (filesystem) module
var fs = require('fs'); // Read the contents of the file into memory.
fs.readFile('myfile.txt', function (err, logData) { // If an error occurred, throwing it will
// display the exception and end our app.
if (err) throw err; // logData is a Buffer, convert to string.
var text = logData.toString(); //converts the byte array into string
console.log(text); });
This is a simple work done without connecting to the server. Node.js makes files I/O really easy with the built in filesystem(fs) module which has a function named readFile that takes a file path and a call back.The file content is read in a form of Buffer as a byte array. This can be converted to string using javascript to read in string form.
Now let's write a server
Creating HTTP Server
var http = require('http'); //requiring http server http.createServer(function (request, response) { response.writeHead(200); response.write("Hello world");//writing hello world in server response.end();//ending the response from server }).listen(8080);//server created port number console.log('Listening on port 8080...');
This will create a basic http server which will have your first "Hello world" written.
You can run this and view on your browser at http://localhost:8080
Asynchronous Call backs
The typical pattern in Node.js is to use asynchronous callbacks. Basically you are
telling it to do something and when it is done it will call your function(call back).
This is because Node is single threaded. While you are waiting on the call back
to fire, Node can go off and do other things instead of blocking until the request
is finished.
- Example for Blocking Call :-
var fs = require('fs'); var contents = fs.readFileSync('myfile.txt'); console.log(contents);console.log('Doing something else');
- call back :-
var callback = function (ree, contents) { console.log(contents); } fs.readFile('second.js',callback);
- A non blocking call with call back :-
fs.readFile('second.js',function (err,contents){ console.log(contents); }); console.log('Doing somethingelse');
Now you may have an understanding of asynchronous call backs done in
Node.js. Also the inbulid function "readFile" under filestream(fs). As we
have now read files in the log and written something in our server, we can
read a file and write it in the server under asynchronous call backs in node.
Reading and writing a file in HTTP server using callback
Let's view our HTML file named "myhtmlfile" in http://localhost:8080 with
asynchronous call back
var fs = require('fs'); var http = require('http'); http.createServer(function (request, response) { response.writeHead(200,{'Content-Type':'text/html'}); //to write a html type file fs.readFile('myhtmlfile.html',function (error,contents) { console.log(contents);//to view the buffer in byte code array response.write(contents); response.end(); }); }).listen(8080); console.log('Listening on port 8080...');You can view write different types of content by defining at the writeHead.
Hopefully now you would have understood the main concepts in node andcan start building your first widget with Node.js.