function MyMainFunction() { } function lessImportantFunction() { } // Replace the exports with main function module.exports = myMainFunction; // Additional functions can be tucked on main module.exports.lessImportantFunction = lessImportantFunction; // Functions for tests can be tucked on under test module.exports.test = { privateFunctionToTest: privateFunction }
function require(name) { var source = findSource(name); var module = { exports: {}}; (function(module, exports){ eval(source); })(module, module.exports); return module;
}
// The benefit of streams readableStream.pipe(writableStream)
var events = require('events'); var util = require('util'); Tapir = function() { this.eat = function(food) { if (isMeat(food)) this.emit('error', new Error("I'm a vegetarian")); else this.emit('eating', food); } }; // Set EventEmitter as Tapir's prototype util.inherits(Tapir, events.EventEmitter);
var fs = require('fs') var file = fs.createReadStream('./file.txt') file.on('error, function(err) { console.log('Error ' + err) throw err; }) file.on('data, function(err) { console.log('Data ' + data) }) file.on('end, function(err) { console.log('End ' + data) })
var writestream = new stream.Stream() writestream.writable = true writestream.write = function (data) { return true // true means 'yes i am ready for more data now' // OR return false and emit('drain') when ready later } writestream.end = function (data) { // no more writes after end // emit "close" (optional) } writestream.write({number: 1}) // note: in node core data is always a buffer or string
var readstream = new stream.Stream() readstream.readable = true readstream.on('data', function(data) { var ready = writestream.write(data) if (ready === false) { this.pause() writestream.once('drain', this.resume.bind(this)) } }) readstream.on('end', function() { writestream.end() })
var r = request.defaults({'proxy':'http://localproxy.com'}) http.createServer(function (req, resp) { if (req.url === '/doodle.png') { r.get('http://google.com/doodle.png').pipe(resp) } })
http://goo.gl/sS8Kv
http://goo.gl/qQVsP