Fork me on GitHub

diet 0.9

Server

# server(options) Function

When diet is required it returns the server function that can be used to create Server Instances.

options object

Server Instance Options. At the moment the only option is `silent` which if set to true disables all logs generated by the Server Instance.

// require diet
var server = require('diet')
	
// create an instance
var app = server()

// create another instance
var anotherApp = server()

// create a silent instance
var silentApp = server({ silent: true })

# app.path string

The path to the app's root directory.

# app.server object

The return value of http.createServer() or https.createServer().

# app.model(path) function

Require a file from "~/yourProject/models/". If your project is at "/Users/adam/yourProject" then it will look within the "models". It will require the file correctly even you call it from nested folders. The models folder needs to exit. Returns module.exports from the file.

path string

The require path within the "models" folder.

# app.controller(path) function

Require a file from "~/yourProject/controllers/". If your project is at "/Users/adam/yourProject" then it will look within the "controllers". It will require the file correctly even you call it from nested folders. The controllers folder needs to exit. Returns module.exports from the file.

path string

The require path within the "controllers" folder.


var home = app.controller('home') // require ~/yourProject/controller/home.js
var user = app.controller('user/permissions') // require  ~/yourProject/controller/user/permissions.js
var post = app.controller('post.js') // require  ~/yourProject/controller/post.js
		

# app.view(type, render) function

Set render function to type.

type string

Choose the view type. Currently html and files are supported.

render(path, context)

The function to run for the view type.


// html engine
var ect = require('ect')({ 
    root  : app.path+'/views/html/', 
    cache : true,
    watch : true,
    ext   : '.html'
})

app.view('html', ect.render)
	

// file handler
var static  = require('diet-static')({ path: app.path+'/views/' });
app.view('file', static)

// http://localhost:8000/any/file.png
// http://localhost:8000/any/other/file.pdf
	

# app.listen(location, httpsOptions) Function

Each server instance has a unique host that is set with app.listen().

location string or object

The location is usually a URL String containing the protocol "http" or "https", following the hostname "ex: localhost" then the port "ex: 8000". The location can also be a URL Object.

httpsOptions object optional

Only required if the protocol is https.

// Create a Server Instance
var app = server()

// HTTP listen with a URL String
app.listen('http://localhost:8000/')

// HTTP listen with a URL Object
app.listen({
    protocol: 'http:',
    hostname: 'localhost',
    port: 8000
})

// HTTPS example
app.listen('https://localhost:8000/', {
    cert: 'secure.crt',
    key: 'key.crt'
})

# app.header([callbacks,...]) Function

Registers callback function(s) to All methods and All Routes. Header functions run after the signal was created and before any Route callbacks and Middleware Modules.

[callbacks...] function or function list

The callback function(s) you want to run before every route. The callbacks have a single argument the GET or POST Signal Object ($) depending on the request method. Note if you are using multiple callbacks, each callback will be executed from the left to right each after the other.

// Create an App
var app = server()                          // Create Server Instance
app.listen('http://localhost:8000/')        // Listen on localhost:8000

// Register a global header function
app.header(function($){
   $.myVariable = 'yolo!'     // create a variable that is accessible in all requests
   $.return()                 // header functions need to be returned
})

// Demonstration
app.get('/somePath', function($){
    $.end('I say ' + $.myVariabLe) // -> I say yolo!
})
app.get('/someOtherPath', function($){
    $.end('I still say ' + $.myVariabLe) // -> I still say yolo!
})

// Register multiple header functions

// First callback
function what($){
    $.what = 'Hello'
    $.return()
}

// Last callback
function who($){
    $.who = 'World'
    $.return()
}

// Register headers 
app.header(what, who)

// Demonstration
app.get('/', function($){
   $.end($.what + ' ' + $.who) // -> Hello World
})

// It is also possible to register headers separately
app.header(what)
app.header(who)

# app.footer([callbacks,...]) Function

Registers callback function(s) to All methods and All Routes. Footer functions run after all Route callbacks and Middleware Modules have been loaded.

[callbacks...] function or function list

The callback function(s) you want to run before every route. The callbacks have a single argument the GET or POST Signal Object ($) depending on the request method. Note if you are using multiple callbacks, each callback will be executed from the left to right each after the other.

// Require dependencies
var path = require('path')
var mime = require('mime')
var server = require('diet')

// Create an app
var app = server()                          // Create Server Instance
app.listen('http://localhost:8000/')        // Listen on localhost:8000

// Register a global footer function that handles static files
// Do not use this in production!
app.footer(function($){
    var pathname   = $.url.pathname
    var mimeType   = mime.lookup(pathname)
    var extension  = path.extname(pathname)
    var source     = app.path + pathname
    
    if(extension){
    	$.header('Content-Type', mimeType)
    	fs.readFile(source, function(error, data){
            if(!error) {
                $.end(data)
                $.return()
            } else if (error.type != 'ENOENT') {
                $.status(error.status || 500, 'File not found');
                $.return();
            } else {
                throw error;
                $.return()
            }
    	})
    } else {
        $.return()
    }
})

// GET http://localhost:8000/hello.png

# app.error([callbacks,...]) Function

Catches errors in every route's middleware and allows to create logs and display user friendly message to clients.

[callbacks...] function or function list

The callback function(s) you want to run on errors. The callbacks have two arguments the GET or POST Signal Object ($) depending on the request method and the middleware object that caused the error.


Note if you are using multiple callbacks, each callback will be executed from the left to right each after the other.

// Create Server Instance
var app = server()

// Subscribe to all error events 
app.error(function($, middleware){
    // Log the error
    console.trace('Something bad happened.', $.status, $.error.message)
    
    // Display error trace in developer environment
    // OR display user friendly message in production environment
    // '<h1>500 Internal Server Error</h1>
    if(process.env.NODE_ENV == 'development'){
        $.return()
    } else {  	
    	$.end('<h1>'+ $.status +' '+ $.statusMessage +'</h1>')
    }
})

# app.missing([callbacks,...]) Function

Registers callbacks for cases when no routes and errors were found for an incoming request.

[callbacks...] function or function list

The callback function(s) you want to run. The callbacks have a single arguments a GET or POST Signal Object ($) depending on the request method.


Note if you are using multiple callbacks, each callback will be executed from the left to right each after the other.

// create an app
var app = server()

// Subscribe to missing event 
app.missing(function($){
    $.end($.status + ' ' + $.statusMessage) // -> 404 not found
})

# app.location Object

The JSON Parsed location attribute from app.listen().

protocol string

The request/response protocol. It can be http: or https:

host string

The complete host including the port.

hostname string

The hostname excluding the port.

port integer

The port.

href string

The full URL

// Create an app
var server = require('diet')
var app = server()
app.listen('http://localhost:8000')

// Log Location
console.log(app.location)

// The above console.log outputs the following object 
// when the path http://localhost:8000/ is requested.
{  protocol: 'http:',
   slashes: true,
   host: 'localhost:8000',
   hostname: 'localhost',
   href: 'http://localhost:8000/' }

# app.get(path, [callbacks,...]) Function

Registers callback function(s) on the GET method with the specified path.

path string

The url path you want to listen to.

[callbacks...] function or function list

The callback function(s) to run when the event is emitted. The callbacks have a single argument the Signal Object ($). Note if you are using multiple callbacks, each callback will be executed from the left to right each after the other.

// Create an app
var app = server()
app.listen('http://localhost:8000/')

// Hello World
app.get('/', function($){
    $.end('welcome home.')
})

// Register multiple callback functions

// First callback
function first($){
    $.who = 'World'
    $.return()
}

// Last callback
function last($){
    $.end('Hello ' + $.who)
}

// Register the callback functions on GET /about
// so that when clients request GET http:/localhost:8000/about
// the server responds with "Hello World"
app.get('/about', first, last)

# app.post(path, [callbacks,...]) Function

Registers callback function(s) on the POST method with the specified path.

path string

The url path you want to listen to.

[callbacks...] function or function list

The callback function(s) to run when the event is emitted. The callbacks have a single argument the Signal Object ($). Note if you are using multiple callbacks, each callback will be executed from the left to right each after the other.

// Create an app
var db = require('models')                  // An example database model
var session = require('session')            // An example session handler middleware module
var app = server()                          // Create Server Instance
app.listen('http://localhost:8000/')        // Listen on localhost:8000

// Example for Single callback function
// Vote anonymously on an issue when requesting 
// POST http:/localhost:8000/vote
app.post('/vote', function($){
    db.vote.create({
        issue   : $.body.issue,
        author  : 'anonymous'
    }, function(error){
    	if(error) throw error
    	$.end('vote successfully submitted')
    })
})

// Example for multiple callback functions
function protected($){
    if($.session){
    	$.return() // Middleware functions need to be returned
    } else {
    	$.end('operation not permitted')   
    }
}

// Register callbacks on GET /about
// "session" uses cookies to get account infos from the db
// "protected" makes sure the session is logged in
app.post('/article', session, protected, function($){
    db.article.create({
        title: $.body.title,
        content: $.body.content,
        author: $.session.id
    }, function(error){
    	if(error) throw error
    	$.end('article created successfully')
    })
})

# app.put(path, [callbacks,...]) Function

Registers callback function(s) on the PUT method with the specified path.

path string

The url path you want to listen to.

[callbacks...] function or function list

The callback function(s) to run when the event is emitted. The callbacks have a single argument the Signal Object ($). Note if you are using multiple callbacks, each callback will be executed from the left to right each after the other.

// PUT http:/localhost:8000/email
app.put('/email', function($){
    $.end('Your Email is ' + $.body.email + '!');
});

# app.head(path, [callbacks,...]) Function

Registers callback function(s) on the HEAD method with the specified path.

path string

The url path you want to listen to.

[callbacks...] function or function list

The callback function(s) to run when the event is emitted. The callbacks have a single argument the Signal Object ($). Note if you are using multiple callbacks, each callback will be executed from the left to right each after the other.

// HEAD http:/localhost:8000/
app.head('/', function($){
    $.end('whatever, no response anyway!');
});

# app.delete(path, [callbacks,...]) Function

Registers callback function(s) on the DELETE method with the specified path.

path string

The url path you want to listen to.

[callbacks...] function or function list

The callback function(s) to run when the event is emitted. The callbacks have a single argument the Signal Object ($). Note if you are using multiple callbacks, each callback will be executed from the left to right each after the other.

// DELETE http:/localhost:8000/
app.delete('/', function($){
    $.end('let me delete something');
});

# app.trace(path, [callbacks,...]) Function

Registers callback function(s) on the TRACE method with the specified path.

path string

The url path you want to listen to.

[callbacks...] function or function list

The callback function(s) to run when the event is emitted. The callbacks have a single argument the Signal Object ($). Note if you are using multiple callbacks, each callback will be executed from the left to right each after the other.

// TRACE http:/localhost:8000/
app.trace('/', function($){
    $.end('trace!');
});

# app.options(path, [callbacks,...]) Function

Registers callback function(s) on the OPTIONS method with the specified path.

path string

The url path you want to listen to.

[callbacks...] function or function list

The callback function(s) to run when the event is emitted. The callbacks have a single argument the Signal Object ($). Note if you are using multiple callbacks, each callback will be executed from the left to right each after the other.

// OPTIONS http:/localhost:8000/
app.options('/', function($){
    $.end('options!');
});

# app.patch(path, [callbacks,...]) Function

Registers callback function(s) on the PATCH method with the specified path.

path string

The url path you want to listen to.

[callbacks...] function or function list

The callback function(s) to run when the event is emitted. The callbacks have a single argument the Signal Object ($). Note if you are using multiple callbacks, each callback will be executed from the left to right each after the other.

// PATCH http:/localhost:8000/
app.patch('/', function($){
    $.end('patch!');
});