fast - Browser Wars work in our favor for speed - Reuse front-end knowledge, less context-switching - Functional (first class function) - Object-Oriented - Most common programming language in the world
- Direct consequence of limiting to a single thread - No legacy compatibility to worry about - All code must purposely be designed around async, less chances of horrible dependencies • Concurrency complexity in the right place - Single-threaded means only utilizing a single core per process - So... start more processes! - You will naturally divide your programs into parts with meaningful interfaces. This puts the complexity in the right place.
and apply them elsewhere? • For some environments, its too late: - Rails is already built, it would require changing everything • Even if it can be done, its already a mixed bag: - Twisted Python is an event-driven networking framework - The entire ecosystem of reusable code would need to be rebuilt to work with it • Real Time Web Apps! - All this stuff is pretty necessary when you start thinking about real-time
fs = require('fs'); // a param that looks like a file path to directly import source var foo = require('./foo'); // expose functions by attaching them to exports global object exports.addOne = function(x) { return x + 1; } // OR expose whole objects by assigning to module.exports function Person(name) { this.name = name; } module.exports = Person;
cannot be returned immediately, // (like when it does some I/O), get results with a callback // you can implement a callback interface for functions you expose var dns = require('dns'); dns.lookup('google.com', function(err, ipAddress) { // NODE CONVENTION: the first parameter given to a callback is the error // check if it is truthy before continuing if (err) return handleError(err); console.log('google.com resolved to %s', ipAddress); }); // you can write functions that return results in a callback too function addOneLater(x, cb) { setTimeout(function() { cb(null, x + 1); }, 200); }
recieving interesting // information from an object over time var net = require('net'); var server = net.createServer(); // when you use the .on() method, its an event emitter server.on('connection', function (stream) { // this will happen over and over every time a connection comes in console.log('someone connected!'); }); server.listen(1337);
= require('http'); http.createServer(function(req, res) { req.on('data', function(chunk) { console.log('got %d bytes of data', chunk.length); }); req.on('end', function() { console.log('end of request'); }); }); // You can get a writable stream to the filesystem var fs = require('fs'); var ws = fs.createWriteStream('tmp.txt'); ws.write('hello world'); ws.end();