What is Nodejs 

Allows you to build scalable network applications using Javascript on the server side.


What could you build


- Websocket Server (like chatting system)
- Fast File Upload Client
- Ad Server
- Any Real-Time Data Apps


What is Node.js not


- web Framework
- for Begineners
- Multi-threaded

 

Objective: Print File contents ( Blocking and Non Blocking Code )


+ Blocking Code
- Read file from Filesystem, set equal to 'contents'
- print contents
- do somethings

+ Non Blocking
- Read file from filesystem, whenever you're complete, print the contents. "whenever you're complete is callback".
- Do something else

 

Blocking vs Non Blocking
+ Blocking

var contents = fs.readFileSync('/etc/hosts');
console.log(contents);
console.log('Doing something else');

+ Non Blocking Code

fs.readFile('/etc/hosts', function(err,contents) {
console.log(contents);
}
console.log('Doing something else');

 

CALLBACK ALTERNATE SYNTAX

fs.readFile('/etc/hosts', function(err, contents) {
console.log(contents);
});

same as

var callback = function(err,contents) {
console.log(contents);
}
fs.readFile('/etc/hosts', callback);

 

Example 1. Node.js Hello my Worlds

var http = require('http');

http.createServer(function (request, response) {
response.writeHead(200); //status code in header
response.write('this is my worlds'); // response body
response.end(); // close response
}).listen(8080); // listening on port 8080
console.log('listening on port 8080...');

save as your file with name hello.js 

open your console and executes with

node hello.js

request same as the event, thats usualy familiar with our javascript everyday.

 

Example 2. Read File 

var http = require('http');
var fs = require('fs');

http.createServer(function(request, response) {
response.writeHead(200);

fs.readFile('index.html', function(err,data){
if(err) throw data;
response.write(data);
response.end();

});
}).listen(8080);

 

Example 3. Read File with content type

var http = require('http');
var fs = require('fs');

http.createServer(function(request, response) {
response.writeHead(200, {'Content-Type':'text/html'});
fs.readFile('index.html', function(err, contents) {
response.write(contents);
response.end();
});

}).listen(8080);

 

Example 4. end with parameter write to body response

var http = require('http');

http.createServer(function(request, response) {
response.writeHead(200);
response.end("Hello, this is my words");
}).listen(8080);

TYPICAL BLOCKING THINGS


- Call out to the web service
- Reads/Write on the Database
- Call to extensions

 

Leave a Comment:



digital_ocean