node.js

let's talk about...



  • Javascript on the server
  • Modules
  • Middleware
  • Express

javascript. on the server!


evented io


built on v8


  • Single-threaded app
  • Written in C++
  • Really *really* fast

core Modules




  • http (s)
  • net
  • fs
  • more...

build your own


/lib/db.js
var mongoose = require('mongoose');

exports.connect = function(connectionString, onConnected) {

	mongoose.connect(connectionString);

	var db = mongoose.connection;
	db.on('error', console.error.bind(console, 'connection error'));	
	db.once('open', function() {
		onConnected();
	});
}




var db = require('./lib/db');
db.connect('mongodb://localhost/test', function() { console.log('connection to mongoose opened'); });

npm



Rapid growth

C++

middleware


  • Connects stuff
  • Plumbing


middleware


e.g.

  • Serving static files
  • logging
  • gzip compression
  • more...

connect




(but there are heaps of other options...)

express



so. many. options.



Getting started


Download the bits from http://nodejs.org/

http

(from nodejs.org documentation)

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(1337);

console.log('Server running at http://127.0.0.1:1337/'); 

connect


var app = connect()
  .use(connect.logger('dev'))
  .use(connect.static('public'))
  .use(function(req, res){
    res.end('hello world\n');
  })
 .listen(3000);

express

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
}); 

show me teh codez!



thanks


Ian Randall


node.js

By ianr

node.js

  • 1,487