Skip to content

Documentation

micnic edited this page Nov 11, 2012 · 94 revisions
var simpleS = require('simples');

New simpleS instance

simples(port)

port: number

simpleS needs only the port number and it sets up a HTTP server on this port.

var server = simples(80);

or

var server = new simples(80);

Server management

Starting and restarting

.start(port, callback)

port: number

callback: function(0)

Start listening for requests on the provided port, if the server is already started, simpleS will restart the server and will listen on the new provided port.

server.start(80, function () {
    // Application logic
});

Stopping

.stop(callback)

callback: function(0)

Stop the server and uses the callback function when server is stopped.

server.stop(function () {
    // Application logic
});

Routing

GET requests

.get(route, callback)

route: string

callback: function(2)

Listen for get requests and uses the callback function with request and response as parameters.

server.get('/', function (request, response) {
    // Application logic
});

POST requests

.post(route, callback)

route: string

callback: function(2)

Listen for post requests and uses the callback function with request and response as parameters.

server.post('/', function (request, response) {
    // Application logic
});

All kind of requests

.all(route, callback)

route: string

callback: function(2)

Listen for all kind of requests and uses the callback function with request and response as parameters.

server.all('/', function (request, response) {
    // Application logic
});

Static files

.getStatic(path)

path: string

path is the local path to a folder that contains static files (for example: css and js files), this folder will serve as the root folder for the server. simleS will return response status 304 (Not Modified) if the files have not been changed since last visit of the client. Only one folder should be used to server static files, if more .getStatic() methods will be called only the last will be used to serve static files. The folder with static files can contain other folders, their content will be also served. The provided path must be relative to the current working directory.

server.getStatic('root');

Inexistent routes

.notFound(callback)

callback: function(2)

Use the callback function with request and response as parameters for undefined routes. Only one callback function can be used for inexistent routes, if more .notFound() methods will be called only the last will be used for routing.

server.notFound(function (request, response) {
    // Application logic
});

Request interface

The first parameter provided in callbacks for routing requests is an object that contains data about the current request. Example:

{
    body: '',
    connection: {
        ip: '127.0.0.1',
        port: 50505
    },
    cookies: [{
        name: 'user',
        value: 'me'
    }, {
        name: 'pass',
        value: 'password'
    }],
    headers: {
        host: 'localhost',
        'user-agent': 'myBrowser',
        accept: 'text/html',
        'accept-language': 'ro;q=0.8,en;q=0.6',
        'accept-encoding': 'gzip, deflate',
        cookie: 'user=me; pass=password'
    },
    langs: [
        'ro',
        'en'
    ],
    method: 'GET',
    query: {
        get: {},
        post: {}
    },
    url: {
        search: '',
        query: {},
        pathname: '/',
        path: '/',
        href: '/'
    }
}

body

The content of the body of the request, for GET requests it is empty, for POST request it will contain plain data, if you need an object representing this query use request.query.post.

connection

Data about the current connection, object containing the remote ip address and the port.

cookies

An array that contains object cookies providing their names and values.

headers

An object that contains the HTTP headers of the request.

langs

An array of strings that represents languages accepted by the client in the order of their relevance.

method

The HTTP method of the request.

query

The object that contains 2 parameters: get - for GET method queries and post - for POST method queries.

url

The url of the request split in components like href, path, pathname, query as object and query as string.

Response interface

The second parameter provided in callbacks for routing requests is a writable stream that defines the data sent to the client. It has the next methods:

.cookie(name, value, config)

name: string

value: string

config: object

Sets the cookies sent to the client, providing a name, a value and an object to configure the expiration time, to limit the domain and the path and to specify if the cookie is http only. Can be used multiple times, but before .write() method. Example:

response.cookie('user', 'me', {
    expires: new Date(new Date().valueOf() + 3600000), // or maxAge: 3600000, default is undefined
    path: '/', // Default is the root of the server
    domain: 'localhost', // Default is the domain of the server
    httpOnly: false, // Default is true
});

.download(filename)

filename: string

Redirects the client to download the provided path. Should not be used with other methods. Example:

response.download('attachement.html');

.lang(language)

language: string

Sets the language of the response. Should be used before the .write() method. Should be used only once. Example:

response.lang('ro');

.redirect(path)

path: string

Redirects the client to the provided path. Should not be used with the other methods. Example:

response.redirect('/index');

.type(type)

type: string

Sets the type of the content of the response. Default is 'html'. Should be used before the .write() method. Should be used only once. Example:

response.type('html');

.write(data)

data: string or buffer

Writes data to the response stream. Should be ended with .end() method. Example:

response.write('Hello');

.end(data)

data: string or empty

If data is provided it calls the .write() method and ends the response. Example:

response.end('World');

WebSocket

WebSocket host

.ws(path, config, callback)

path: string

config: object

callback: function(1)

Listen for WebSocket connections. For security reasons origins and protocols should be provided in the config parameter, the length of the message can be limited, default is 1MB. The callback function comes with the connection as parameter.

server.ws('/', {
    messageMaxLength: 1024,
    origins: ['null'],
    protocols: ['chat']
}, function (connection) {
    // Application logic
});

WebSocket connection

The object that represents the current WebSocket connection. The WebSocket connection is an event emitter. It has the next methods:

.getConnections()

Return all the connections that exist at the moment.

.getOrigin()

Return the origin of the WebSocket connection

.getProtocols()

Return the array of protocols of the WebSocket connection

.getRequest()

Return the HTTP request made by the client to create this WebSocket connection.

.getSocket()

Return the TCP socket used to maintain this WebSocket connection.

.send(data)

data: string or buffer

Sends a message to the client. If data is a buffer then the sent message will be of binary type, else - text type, objects, arrays and numbers are stringified.

.broadcast(data, filter)

data: string or buffer

filter: function(3)

Sends a message to all connected clients. Clients can be filtered by providing the second parameter, equivalent to Array.filter(). Example:

connection.broadcast('HelloWorld', function (element, index, array) {
    return element.getProtocols().indexOf('chat') >= 0; // Will send the message to clients that use "chat" as a subprotocol
});

The WebSocket connection has the next events:

message

Emitted when the server receives a message from the client.

close

Emitted when the connection is closed.

Clone this wiki locally