Express

High performance web framework for node.

index

lib/express/index.js

Framework version.

exports.version = '0.14.0';

Module dependencies.

var Server = require('./server');

Shortcut for new Server(...).

  • param: Function …

  • return: Server

  • api: public

p>
exports.createServer = function(){
    return new Server(Array.prototype.slice.call(arguments));
};

View extensions.

require('./view');
require('./response');

response

lib/express/response.js

Module dependencies.

var http = require('http'),
    path = require('path'),
    mime = require('connect/utils').mime,
    Buffer = require('buffer').Buffer;

Send a response with the given body and optional headers and status code.

Currently supports:

  • html
  • json

  • param: String | Object body

  • param: Object headers

  • param: Number status

  • return: ServerResponse

  • api: public

http.ServerResponse.prototype.send = function(body, headers, status){
    status = status || 200;
    headers = headers || {};
    switch (typeof body) {
        case 'string':
            headers['Content-Type'] = 'text/html; charset=utf8';
            break;
        case 'object':
            headers['Content-Type'] = 'application/json; charset=utf8';
            body = JSON.stringify(body);
            break;
    }
    headers['Content-Length'] = Buffer.byteLength(body);
    this.writeHead(status, headers);
    this.end(body);
};

Set Content-Type response header passed through mime.type().

Examples

var filename = 'path/to/image.png';
res.contentType(filename);
// => "image/png"

  • param: String type

  • return: String the resolved mime type

  • api: public

http.ServerResponse.prototype.contentType = function(type){
    return this.headers['Content-Type'] = mime.type(type);
};

server

lib/express/server.js

Module dependencies.

var sys = require('sys'),
    connect = require('connect'),
    router = require('connect/middleware/router');

Initialize a new Server with optional middleware.

  • param: Array middleware

  • api: public

var Server = exports = module.exports = function Server(middleware){
    var self = this;
    this.config = {};
    this.settings = {};
    connect.Server.call(this, middleware || []);

    // Expose app to extensions
    this.use('/', function(req, res, next){
        req.app = res.app = self;
        next();
    });

    // Use router, expose as app.get(), etc
    this.use('/', router(function(app){
        self.routes = app;
    }));
};

Inherit from connect.Server.

?YQ
sys.inherits(Server, connect.Server);

Listen on the given port after running configuration blocks.

  • param: Number port

  • api: public

Server.prototype.listen = function(port){
    var env = process.env.EXPRESS_ENV || process.connectEnv.name;
    this.runConfig('any', env);
    connect.Server.prototype.listen.call(this, port);
};

Run config callbacks for the given environment(s);

  • param: String env …

  • return: Server for chaining

  • api: public

Server.prototype.runConfig = function(){
    for (var i = 0, len = arguments.length; i < len; ++i) {
        var env = arguments[i];
        if (env in this.config) {
            var config = this.config[env];
            config.forEach(function(fn){
                fn.call(this);
            }, this);
        }
    }
    return this;
};

Assign setting to val, or return setting’s value.

  • param: String setting

  • param: String val

  • return: Server | Mixed for chaining, or the setting value

  • api: public

Server.prototype.set = function(setting, val){
    if (val === undefined) {
        return this.settings[setting];
    } else {
        this.settings[setting] = val;
        return this;
    }
};

Enable setting.

  • param: String setting

  • return: Server for chaining

  • api: public

Server.prototype.enable = function(setting){
    return this.set(setting, true);
};

Disable setting.

  • param: String setting

  • return: Server for chaining

  • api: public

Server.prototype.disable = function(setting){
    return this.set(setting, false);
};

Disable setting.

  • param: String setting

  • return: Server for chaining

  • api: public

Server.prototype.configure = function(env, fn){
    if (typeof env === 'function') fn = env, env = 'any';
    (this.config[env] = this.config[env] || []).push(fn);
    return this;
};

// Generate RESTful methods

(function(method){
    Server.prototype[method] = function(path, fn){
        this.routes[method](path, fn);
        return this;
    };
    return arguments.callee;
})('get')('post')('put')('del');

view

lib/express/view.js

Module dependencies.

var extname = require('path').extname,
    mime = require('connect/utils').mime,
    http = require('http'),
    fs = require('fs');

Cache supported template engine exports to increase performance by lowering the number of calls to require().

  • type: Object
var cache = {};

// TODO: assume same extension for partials / layout when not present
// TODO: when extension not given, auto-discover
// TODO: error handling

Render view partial with the given options.

Options

  • as String name for the id used to which “collection” assign it’s current value.
  • collection Array of objects, the name is derived from the view name itself. For example video.html will have a object video available to it.

  • param: String view

  • param: Object options

  • return: String

  • api: public

http.ServerResponse.prototype.partial = function(view, options){
    options = options || {};
    options.partial = true;
    options.layout = false;
    var collection = options.collection;
    if (collection) {
        var name = options.as || view.split('.')[0],
            len = collection.length;
        var locals = options.locals = options.locals || {};
        locals.collectionLength = len;
        return collection.map(function(val, i){
            locals[name] = val;
            locals.firstInCollection = i === 0;
            locals.indexInCollection = i;
            locals.lastInCollection = i === len - 1;
            return this.render(view, options);
        }, this).join('');
    } else {
        return this.render(view, options);
    }
};

Render view with the given options and optional callback fn. When a callback function is given a response will not be made automatically, however otherwise a response of 200 and text/html is given.

  • param: String view

  • param: Object options

  • param: Function fn

  • api: public

http.ServerResponse.prototype.render = function(view, options, fn){
    options = options || {};

    // Defaults
    var self = this,
        ext = extname(view),
        partial = options.partial,
        root = options.root || this.app.set('views') || process.cwd() + '/views',
        layout = options.layout === undefined ? true : options.layout,
        layout = layout === true
            ? 'layout' + ext
            : layout;

    // Always expose partial() as a local
    options.locals = options.locals || {};
    options.locals.partial = function(){
        self.partial.apply(self, arguments);
    };

    // Partials support
    if (options.partial) {
        root += '/partials';
    }

    // View path
    var path = root + '/' + view;

    // Send response
    function send(str) {
        self.writeHead(200, {
            'Content-Type': 'text/html',
            'Content-Length': str.length
        });
        self.end(str);
    }
    
    // Pass filename to the engine
    options.filename = path;

    function error(err) {
        if (fn) {
            fn(err);
        } else {
            throw err;
        }
    }

    // Render
    fs.readFile(path, 'utf8', function(err, str){
        if (err) {
            error(err);
        } else {
            var engine = cache[ext] || (cache[ext] = require(ext.substr(1)));
            try {
                str = engine.render(str, options);
            } catch (err) {
                error(err);
            }
            if (layout) {
                options.layout = false;
                options.locals.body = str;
                self.render(layout, options);
            } else if (partial) {
                return str;
            } else if (fn) {
                fn(null, str);
            } else {
                send(str);
            }
        }
    });
};