I N T R O T O N O D E . J S
- L E V E L O N E -
INTRO TO NODE.JS
WHAT IS NODE.JS?
It’s fast because it’s mostly C code
Allows you to build scalable network
applications using JavaScript on the server-side.
V8 JavaScript Runtime
Node.js
INTRO TO NODE.JS
WHAT COULD YOU BUILD?
• Websocket Server
• Fast File Upload Client
• Ad Server
• Any Real-Time Data Apps
Like a chat server
INTRO TO NODE.JS
WHAT IS NODE.JS NOT ?
• A Web Framework
• For Beginners It’s very low level
• Multi-threaded
You can think of it as a single threaded server
INTRO TO NODE.JS
OBJECTIVE: PRINT FILE CONTENTS
This is a “Callbackâ€
Read file from Filesystem, set equal to “contentsâ€
Print contents
• Blocking Code
• Non-Blocking Code
Do something else
Read file from Filesystem
whenever you’re complete, print the contents
Do Something else
console.log(contents);
INTRO TO NODE.JS
BLOCKING VS NON-BLOCKING
var contents = fs.readFileSync('/etc/hosts');
console.log(contents);
console.log('Doing something else');
• Blocking Code
• Non-Blocking Code
console.log('Doing something else');
Stop process until
complete
fs.readFile('/etc/hosts', function(err, contents) {
});
fs.readFile('/etc/hosts', function(err, contents) {
console.log(contents);
});
INTRO TO NODE.JS
CALLBACK ALTERNATE SYNTAX
var callback = function(err, contents) {
console.log(contents);
}
fs.readFile('/etc/hosts', callback);
Same as
INTRO TO NODE.JS
BLOCKING VS NON-BLOCKING
blocking
0s
non-blocking
10s5s
0s 10s5s
fs.readFile('/etc/hosts', callback);
fs.readFile('/etc/inetcfg', callback);
var callback = function(err, contents) {
console.log(contents);
}
hello.js
NODE.JS HELLO DOG
$ curl http://localhost:8080
Hello, this is dog.
How we require modules
Status code in header
Response body
Close the connection
Listen for connections on this port
$ node hello.js Run the server
var http = require('http');
http.createServer(function(request, response) {
response.writeHead(200);
response.write("Hello, this is dog.");
response.end();
}).listen