What is Node.js
Writing Node
The fs Module
Consuming APIs,
Client Routing
HTTP protocol
IP protocol
DNS
CDNs
Networking
Request Routing,
Asset Delivery,
Creating APIs,
Databases,
Data Processing
Consuming APIs,
Client Routing
HTTP protocol
IP protocol
DNS
CDNs
Networking
Request Routing,
Asset Delivery,
Creating APIs,
Databases,
Data Processing
Request Routing,
Asset Delivery,
Creating APIs,
Databases,
Data Processing
A program
A program
That runs on your computer
A program
That runs on your computer
That executes JavaScript
A program
That runs on your computer
That executes JavaScript
ECMAScript 2015... ish
ECMAScript 2015... ish
No access to Browser APIs
document
window
New Features!
Module System!
Node Package Manager (NPM)
$ node
- A program on your computer that runs JavaScript
$ node
- A program on your computer that runs JavaScript
$ npm
- Node Package Manager, like `brew` for node!
$ node
var greeting = "Hello, ";
console.log(greeting + "class!");
To start:
$ node greeting.js
Hello, class!
greeting.js:
$ node
$ node
$ node
Filesystem
HTTP / HTTPS
OS
C / C++ Wrappers (for Internet of Things!)
Network
$ node
$ node
$ node
moduleName.asyncMethod("param1", function(err, data) {
//err will be empty if there was no error
if (!err) {
doSomethingWith(data);
} else {
console.log("there was an error!" + err);
}
});
A typical node.js pattern - Async I/O
These do something asynchronous, and then execute a callback
$ node
var eventEmitter = moduleName.createEventEmitter("thing");
eventEmitter.on("someEvent", function(err, data){
console.log(err);
console.log(data);
});
eventEmitter.on("someOtherEvent", function(err, result) {
if (err) throw err;
console.log(result);
});
A typical node.js pattern - Evented I/O
These events can happen in any order!
$ node
Using Modules
var myModule = require("aModule");
module.doSomething()
var thing = module.createSomething();
thing.on("event", function(){
// do something
});
thing.doSomethingAsync(params, function(){
// do something when done
});
$ node
var os = require("os");
os.hostname();
os.networkInterfaces();
os.uptime();
OS - just read access
$ node
Filesystem - Async pattern
var fs = require("fs");
fs.readFile("./log.txt", function(err, data){
var myFile = data.toString();
console.log(myFile)
});
$ node
var http = require("http");
var server = http.createServer();
server.on("request", function(request, response) {
response.end("Hello");
});
server.listen(9021, function(err){
if (err) {
console.log(err);
} else {
console.log("I've connected!");
}
});
HTTP / HTTPS - Evented