2. What is Node.js?
Node is a way to use Javascript outside the
browser, on the server side.
At it's core, it's a command line version of
Javascript.
node script.js
How does this let you serve webpages?
3. The Modular Server
● Out of the box, node can't serve webpages
● Handling HTTP requests happens with a
module (express)
● Routing, Authentication and Database layers
are all separate modules
● Find and install node modules with 'npm'
● You wire the modules together with code
4. Modular Example
// to serve a webpage
var express = require('express');
// login module
var passport = require('passport');
// provide a callback for the index
var app = express();
app.get("/", function(......
// require authentication
app.use(passport.initialize());
5. Express, the webserver
When node.js needs to act as a webserver,
typically you use express.
Express handles listening on a port for HTTP
requests and responses
In typical node.js fashion, express has many
modules handling JSON parsing, basic
authentication, sessions and more.
6. Express "Hello World"
var express = require('express');
var app = express();
app.get('/hello.txt', function(req, res){
var body = 'Hello World';
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', body.length);
res.end(body);
});
app.listen(80);
7. Socket.io
Socket.io is used to communicate with the
browser's Javascript app.
When using client-side apps, such as
Backbone or KnockoutJS, you can
communicate changes to node.js for saving to
a database
Socket.io is lightweight and responsive, for
real-time server-client communication
8. Socket.io Example
Server
var io = require('socket.io').listen(8080);
io.sockets.on('connection', function (socket) {
socket.on('data:save', function (data) {
// save data to database
});
});
Client
<script>
var socket = io.connect('http://localhost');
// save data to server's database
socket.emit('data:save', { my: 'data' });
</script>
9. Scaling with Cluster
Node.js, like Javascript, only has one thread!
For a webserver, this makes every request wait
on the previous request to complete before
being processed.
Fortunately, cluster let's you start the same
node.js script in multiple threads. Similar to C's
"fork" method
10. Cluster Example
var cluster = require('cluster');
if (cluster.isMaster) {
require('os').cpus().forEach(
function () {
cluster.fork();
});
} else {
// Serve your app, this code will
// run multiple times, once for
// each CPU on your server
}
11. Many more modules!
● Mongoose to communicate with MongoDB
● 'fs' for using the server's filesystem
● 'vm' for running new sandboxed Javascripts
● 'node-mysql' for MySql
● Lots more! Use 'npm search' to find any
module you want!