View
779
Download
1
Embed Size (px)
DESCRIPTION
An introduction to Node.JS -- why its cool and useful and powerful. Allen Cook's slides from his presentation to the KYJSUG on Feb 28.
Citation preview
Node.jsJavascript outside the browser
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?
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
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());
Express, the webserverWhen 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.
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);
Socket.ioSocket.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
Socket.io ExampleServervar 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>
Scaling with ClusterNode.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
Cluster Examplevar 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}
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!
Questions?