Node.js
Introduction
by
Jezeniel Zapanta
What is Node.js?
- It is a server side Javascript.
- Is a wrapper on top of the V8 Javascript runtime
- Uses an event-driven, non-blocking I/O
What is a non-blocking I/O?
Blocking (Synchronous)
from time import sleep
sleep(5)
print "Hello"
sleep(5)
print "World!"
print "Hi!"
<?php
sleep(5);
echo "Hello";
sleep(5);
echo "World!";
echo "Hi!";
?>
Python
PHP
Non-blocking (Asynchronous)
setTimeout(function() {
console.log("Hello");
}, 5000);
setTimeout(function() {
console.log("Word!");
}, 6000);
console.log("Hi!");
More Examples
Blocking
Non-blocking
var fs = require('fs');
var contents = fs.readFileSync("foo.txt");
console.log(contents.toString());
console.log("Hi.");
var fs = require('fs');
fs.readFile("foo.txt", function(err, contents) {
console.log(contents.toString());
});
console.log("Hi.");
The Callback
var fs = require('fs');
var contents = fs.readFile("foo.txt", function(err, contents) {
// This is a callback
console.log(contents.toString());
});
console.log("Hi.");
Alternate syntax
var fs = require('fs');
/*
function outputContent(err, contents) {
console.log(contents.toString());
}
*/
var outputContent = function(err, contents) {
console.log(contents.toString());
};
fs.readFile("foo.txt", outputContent);
fs.readFile("foo2.txt", outputContent);
console.log("Hi.");
Example Webserver
var http = require('http');
var server = http.createServer(function(request, response) {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.write('Hello \n');
response.end('World!\n');
});
server.listen(8080, '0.0.0.0');
console.log('Server running at http://0.0.0.0:8080');
WTH is event loop?
What can I build with Node.js?
- Real-time Applications
- Chat
- Data Streaming
- Multiplayer games
- File Upload Client
- API Service
Node.js is not...
- A Web framework
- For beginners
- Multi-threaded
Questions?
References
HAU Talk
By Jezeniel Zapanta
HAU Talk
- 391