### serverbuilder

`3.1.0`
Need help reading this?

### index

Module exports.

index

### index

Module exports.

index

### index

Module exports.

index

### index

Module exports.

index

### index

Module exports.

index

### index

Module exports.

index

### Server

Re-usable server.

new Server(associatedApp: express, port: (string | number), opts: {name: string, useHttps: boolean, useHttp2: boolean, securityOptions: object, callback: function (Server), showPublicIP: boolean, silent: boolean, gracefulClose: boolean, autoRun: boolean})
Parameters
associatedApp `(express)` Associated express application
port `((string | number) = `(process.env.PORT||3e3)`)` Port/pipe to use
opts `({name: string, useHttps: boolean, useHttp2: boolean, securityOptions: object, callback: function (Server), showPublicIP: boolean, silent: boolean, gracefulClose: boolean, autoRun: boolean} = `{name:'Server',useHttps:false,securityOptions:{},callback:(server)=>{},showPublicIP:false,silent:false,gracefulClose:true,autoRun:false}`)` Options including the server's name, HTTPS, options needed for the HTTPs server (public keys and certificates), callback called within the `listen` event and whether it should show its public IP and whether it needs to be silent ( which won't affect the public IP log ) and if it should run automatically upon being instantiated.
Static Members
▸ app

Get the associated application (Express instance).

app
Returns
`express`: Associated Express instance
▸ app

Set the Express application associated to the router.

app
Parameters
value `(express)` Express app
▸ port

Get the port/pipe of used by the server.

port
Returns
`(number | string)`: Port/pipes
▸ port

Change the port/pipe of the server without affecting the server instance.
Use this method at your own risk!

port
Parameters
value `((number | string))` New port/pipe
▸ name

Get the server's name.

name
Returns
`string`: Name
▸ name

Change the server's name.

name
Parameters
value `(string)` New name
▸ useHttps

See if whether or not the server is using HTTPS.

useHttps
Returns
`boolean`: S flag
▸ useHttps

Changes the HTTPS flag without affecting the server instance.
Use this method at your own risk!

useHttps
Parameters
value `(boolean)` New flag
▸ useHttp2

See if whether or not the server is using HTTP/2.

useHttp2
Returns
`boolean`: Version 2 flag
▸ useHttp2

Changes the HTTP version flag without affecting the server instance.
Use this method at your own risk!

useHttp2
Parameters
value `(boolean)` New flag
▸ options

Get the server options (that is the ones used for the HTTPS and HTTP/2 mode).

options
Returns
`Object`: Options
▸ options

Change the server options without affecting the server instance.
Use this method at your own risk!

options
Parameters
value `(Object)` New options
▸ server

Get the server's instance.

server
Returns
`(http.Server | https.Server | http2.Server)`: Server instance
▸ server

Change the server's instance.
However it's recommended to restart the server otherwise the event handlers won't work properly.

server
Parameters
value `((http.Server | https.Server | http2.Server))` New server instance
▸ silent

Get the silent flag.

silent
Returns
`boolean`: Server's silence
▸ silent

Change the server' silence.

silent
Parameters
value `(boolean)` New silence mode
▸ run()

Run/start the server.

run(): (http.Server | https.Server | http2.Server)
Returns
`(http.Server | https.Server | http2.Server)`: Server
Throws

- Error: Running error

▸ onError(error)

Event listener for HTTP server "error" event.

onError(error: Error): function (Error)
Parameters
error `(Error)` Error to handle
Returns
`function (Error)`: Error handler
Throws

- Error: EACCES/EADDRINUSE/ENOENT errors

▸ close()

Gracefully close the server.

close(): Promise
Returns
`Promise`: Closure promise
Throws

- Error: Closing error

▸ toString()

Textual representation of a Server object.

toString(): string
Returns
`string`: Server object in text

### bodyParser

Create a middleware to parse json and urlencoded bodies.

bodyParser(options: object?): function
Deprecated: This is deprecated.
Parameters
options `(object?)`
Returns
`function`:

### View

Initialize a new `View` with the given `name`.

Options:

- `defaultEngine` the default template engine name
- `engines` template engine require() cache
- `root` root path for view lookup

new View(name: string, options: object)
Parameters
name `(string)`
options `(object)`

### Route

Initialize `Route` with the given `path`,

new Route(path: String)
Parameters
path `(String)`

### proto

Initialize a new `Router` with the given `options`.

proto
Parameters
options `(Object?)`
Returns
`Router`: which is an callable function
Static Members
▸ param(name, fn)

Map the given param placeholder `name`(s) to the given callback.

Parameter mapping is used to provide pre-conditions to routes which use normalized placeholders. For example a :user_id parameter could automatically load a user's information from the database without any additional code,

The callback uses the same signature as middleware, the only difference being that the value of the placeholder is passed, in this case the id of the user. Once the `next()` function is invoked, just like middleware it will continue on to execute the route, or subsequent parameter functions.

Just like in middleware, you must either respond to the request or call next to avoid stalling the request.

app.param('user_id', function(req, res, next, id){ User.find(id, function(err, user){ if (err) { return next(err); } else if (!user) { return next(new Error('failed to load user')); } req.user = user; next(); }); });

param(name: String, fn: Function): app
Parameters
name `(String)`
fn `(Function)`
Returns
`app`: for chaining
▸ use(fn)

Use the given middleware function, with optional path, defaulting to "/".

Use (like `.all`) will run for any http METHOD, but it will not add handlers for those methods so OPTIONS requests will not consider `.use` functions even if they could respond.

The other difference is that route path is stripped and not visible to the handler function. The main effect of this feature is that mounted handlers can operate without any code changes regardless of the "prefix" pathname.

use(fn: any)
Parameters
fn `(any)`
▸ route(path)

Create a new Route for the given path.

Each route contains a separate middleware stack and VERB handlers.

See the Route api documentation for details on adding handlers and middleware to routes.

route(path: String): Route
Parameters
path `(String)`
Returns
`Route`:

### req

Request prototype.

req
Static Members
▸ get

Return request header.

The `Referrer` header field is special-cased, both `Referrer` and `Referer` are interchangeable.

Examples:

    req.get('Content-Type');
    // => "text/plain"

    req.get('content-type');
    // => "text/plain"

    req.get('Something');
    // => undefined

Aliased as `req.header()`.

get
Parameters
name `(String)`
Returns
`String`:
▸ accepts(type)

To do: update docs.

Check if the given `type(s)` is acceptable, returning the best match when true, otherwise `undefined`, in which case you should respond with 406 "Not Acceptable".

The `type` value may be a single MIME type string such as "application/json", an extension name such as "json", a comma-delimited list such as "json, html, text/plain", an argument list such as `"json", "html", "text/plain"`, or an array `["json", "html", "text/plain"]`. When a list or array is given, the best match, if any is returned.

Examples:

    // Accept: text/html
    req.accepts('html');
    // => "html"

    // Accept: text/*, application/json
    req.accepts('html');
    // => "html"
    req.accepts('text/html');
    // => "text/html"
    req.accepts('json, text');
    // => "json"
    req.accepts('application/json');
    // => "application/json"

    // Accept: text/*, application/json
    req.accepts('image/png');
    req.accepts('png');
    // => undefined

    // Accept: text/*;q=.5, application/json
    req.accepts(['html', 'json']);
    req.accepts('html', 'json');
    req.accepts('html, json');
    // => "json"

accepts(type: (String | Array)): (String | Array | Boolean)
Parameters
type `((String | Array))` (s)
Returns
`(String | Array | Boolean)`:
▸ acceptsEncodings()

Check if the given `encoding`s are accepted.

acceptsEncodings(): (String | Array)
Returns
`(String | Array)`:
▸ acceptsCharsets()

Check if the given `charset`s are acceptable, otherwise you should respond with 406 "Not Acceptable".

acceptsCharsets(): (String | Array)
Returns
`(String | Array)`:
▸ acceptsLanguages()

Check if the given `lang`s are acceptable, otherwise you should respond with 406 "Not Acceptable".

acceptsLanguages(): (String | Array)
Returns
`(String | Array)`:
▸ range(size, options?)

Parse Range header field, capping to the given `size`.

Unspecified ranges such as "0-" require knowledge of your resource length. In the case of a byte range this is of course the total number of bytes. If the Range header field is not given `undefined` is returned, `-1` when unsatisfiable, and `-2` when syntactically invalid.

When ranges are returned, the array has a "type" property which is the type of range that is required (most commonly, "bytes"). Each array element is an object with a "start" and "end" property for the portion of the range.

The "combine" option can be set to `true` and overlapping & adjacent ranges will be combined into a single range.

NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" should respond with 4 users when available, not 3.

range(size: number, options: object?): (number | array)
Parameters
size `(number)`
options `(object?)`

Name | Description
--- | ---
options.combine `boolean` (default `false`) |

Returns
`(number | array)`:
▸ param(name, defaultValue?)

Return the value of param `name` when present or `defaultValue`.

- Checks route placeholders, ex: /user/:id
- Checks body params, ex: id=12, {"id":12}
- Checks query string params, ex: ?id=12

To utilize request bodies, `req.body` should be an object. This can be done by using the `bodyParser()` middleware.

param(name: String, defaultValue: Mixed?): String
Parameters
name `(String)`
defaultValue `(Mixed?)`
Returns
`String`:
▸ is(types)

Check if the incoming request contains the "Content-Type" header field, and it contains the give mime `type`.

Examples:

     // With Content-Type: text/html; charset=utf-8
     req.is('html');
     req.is('text/html');
     req.is('text/*');
     // => true

     // When Content-Type is application/json
     req.is('json');
     req.is('application/json');
     req.is('application/*');
     // => true

     req.is('html');
     // => false

is(types: any): (String | `false` | null)
Parameters
types `(any)`
Returns
`(String | `false` | null)`:

### defineGetter

Return the protocol string "http" or "https" when requested with TLS. When the "trust proxy" setting trusts the socket address, the "X-Forwarded-Proto" header field will be trusted and used if present.

If you're running behind a reverse proxy that supplies https for you this may be enabled.

defineGetter
Returns
`String`:

### defineGetter

Short-hand for:

req.protocol === 'https'

defineGetter
Returns
`Boolean`:

### defineGetter

Return the remote address from the trusted proxy.

The is the remote address on the socket unless "trust proxy" is set.

defineGetter
Returns
`String`:

### defineGetter

When "trust proxy" is set, trusted proxy addresses + client.

For example if the value were "client, proxy1, proxy2" you would receive the array `["client", "proxy1", "proxy2"]` where "proxy2" is the furthest down-stream and "proxy1" and "proxy2" were trusted.

defineGetter
Returns
`Array`:

### defineGetter

Return subdomains as an array.

Subdomains are the dot-separated parts of the host before the main domain of the app. By default, the domain of the app is assumed to be the last two parts of the host. This can be changed by setting "subdomain offset".

For example, if the domain is "tobi.ferrets.example.com": If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. If "subdomain offset" is 3, req.subdomains is `["tobi"]`.

defineGetter
Returns
`Array`:

### defineGetter

Short-hand for `url.parse(req.url).pathname`.

defineGetter
Returns
`String`:

### defineGetter

Parse the "Host" header field to a hostname.

When the "trust proxy" setting trusts the socket address, the "X-Forwarded-Host" header field will be trusted.

defineGetter
Returns
`String`:

### defineGetter

Check if the request is fresh, aka Last-Modified and/or the ETag still match.

defineGetter
Returns
`Boolean`:

### defineGetter

Check if the request is stale, aka "Last-Modified" and / or the "ETag" for the resource has changed.

defineGetter
Returns
`Boolean`:

### defineGetter

Check if the request was an XMLHttpRequest.

defineGetter
Returns
`Boolean`:

### res

Response prototype.

res
Static Members
▸ status(code)

Set status `code`.

status(code: Number): ServerResponse
Parameters
code `(Number)`
Returns
`ServerResponse`:
▸ links(links)

Set Link header field with the given `links`.

Examples:

res.links({ next: 'http://api.example.com/users?page=2', last: 'http://api.example.com/users?page=5' });

links(links: Object): ServerResponse
Parameters
links `(Object)`
Returns
`ServerResponse`:
▸ send(body)

Send a response.

Examples:

    res.send(Buffer.from('wahoo'));
    res.send({ some: 'json' });
    res.send('<p>some html</p>');

send(body: (string | number | boolean | object | Buffer))
Parameters
body `((string | number | boolean | object | Buffer))`
▸ json(obj)

Send JSON response.

Examples:

    res.json(null);
    res.json({ user: 'tj' });

json(obj: (string | number | boolean | object))
Parameters
obj `((string | number | boolean | object))`
▸ jsonp(obj)

Send JSON response with JSONP callback support.

Examples:

    res.jsonp(null);
    res.jsonp({ user: 'tj' });

jsonp(obj: (string | number | boolean | object))
Parameters
obj `((string | number | boolean | object))`
▸ sendStatus(statusCode)

Send given HTTP status code.

Sets the response status to `statusCode` and the body of the response to the standard description from node's http.STATUS_CODES or the statusCode number if no description.

Examples:

    res.sendStatus(200);

sendStatus(statusCode: number)
Parameters
statusCode `(number)`
▸ sendFile(path, options, callback)

Transfer the file at the given `path`.

Automatically sets the Content-Type response header field. The callback `callback(err)` is invoked when the transfer is complete or when an error occurs. Be sure to check `res.sentHeader` if you wish to attempt responding, as the header and some data may have already been transferred.

Options:

- `maxAge` defaulting to 0 (can be string converted by `ms`)
- `root` root directory for relative filenames
- `headers` object of headers to serve with file
- `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them

Other options are passed along to `send`.

Examples:

The following example illustrates how `res.sendFile()` may be used as an alternative for the `static()` middleware for dynamic situations. The code backing `res.sendFile()` is actually the same code, so HTTP cache support etc is identical.

    app.get('/user/:uid/photos/:file', function(req, res){
      var uid = req.params.uid
        , file = req.params.file;

      req.user.mayViewFilesFrom(uid, function(yes){
        if (yes) {
          res.sendFile('/uploads/' + uid + '/' + file);
        } else {
          res.send(403, 'Sorry! you cant see that.');
        }
      });
    });

sendFile(path: any, options: any, callback: any)
Parameters
path `(any)`
options `(any)`
callback `(any)`
▸ sendfile(path, options, callback)

Transfer the file at the given `path`.

Automatically sets the Content-Type response header field. The callback `callback(err)` is invoked when the transfer is complete or when an error occurs. Be sure to check `res.sentHeader` if you wish to attempt responding, as the header and some data may have already been transferred.

Options:

- `maxAge` defaulting to 0 (can be string converted by `ms`)
- `root` root directory for relative filenames
- `headers` object of headers to serve with file
- `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them

Other options are passed along to `send`.

Examples:

The following example illustrates how `res.sendfile()` may be used as an alternative for the `static()` middleware for dynamic situations. The code backing `res.sendfile()` is actually the same code, so HTTP cache support etc is identical.

    app.get('/user/:uid/photos/:file', function(req, res){
      var uid = req.params.uid
        , file = req.params.file;

      req.user.mayViewFilesFrom(uid, function(yes){
        if (yes) {
          res.sendfile('/uploads/' + uid + '/' + file);
        } else {
          res.send(403, 'Sorry! you cant see that.');
        }
      });
    });

sendfile(path: any, options: any, callback: any)
Parameters
path `(any)`
options `(any)`
callback `(any)`
▸ download(path, filename, options, callback)

Transfer the file at the given `path` as an attachment.

Optionally providing an alternate attachment `filename`, and optional callback `callback(err)`. The callback is invoked when the data transfer is complete, or when an error has ocurred. Be sure to check `res.headersSent` if you plan to respond.

Optionally providing an `options` object to use with `res.sendFile()`. This function will set the `Content-Disposition` header, overriding any `Content-Disposition` header passed as header options in order to set the attachment and filename.

This method uses `res.sendFile()`.

download(path: any, filename: any, options: any, callback: any)
Parameters
path `(any)`
filename `(any)`
options `(any)`
callback `(any)`
▸ contentType

Set Content-Type response header with `type` through `mime.lookup()` when it does not contain "/", or set the Content-Type to `type` otherwise.

Examples:

    res.type('.html');
    res.type('html');
    res.type('json');
    res.type('application/json');
    res.type('png');

contentType
Parameters
type `(String)`
Returns
`ServerResponse`: for chaining
▸ format(obj)

Respond to the Acceptable formats using an `obj` of mime-type callbacks.

This method uses `req.accepted`, an array of acceptable types ordered by their quality values. When "Accept" is not present the first callback is invoked, otherwise the first match is used. When no match is performed the server responds with 406 "Not Acceptable".

Content-Type is set for you, however if you choose you may alter this within the callback using `res.type()` or `res.set('Content-Type', ...)`.

res.format({ 'text/plain': function(){ res.send('hey'); },

     'text/html': function(){
       res.send('<p>hey</p>');
     },

     'appliation/json': function(){
       res.send({ message: 'hey' });
     }

});

In addition to canonicalized MIME types you may also use extnames mapped to these types:

res.format({ text: function(){ res.send('hey'); },

     html: function(){
       res.send('<p>hey</p>');
     },

     json: function(){
       res.send({ message: 'hey' });
     }

});

By default Express passes an `Error` with a `.status` of 406 to `next(err)` if a match is not made. If you provide a `.default` callback it will be invoked instead.

format(obj: Object): ServerResponse
Parameters
obj `(Object)`
Returns
`ServerResponse`: for chaining
▸ attachment(filename)

Set Content-Disposition header to attachment with optional `filename`.

attachment(filename: String): ServerResponse
Parameters
filename `(String)`
Returns
`ServerResponse`:
▸ append(field, val)

Append additional header `field` with value `val`.

Example:

res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']); res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); res.append('Warning', '199 Miscellaneous warning');

append(field: String, val: (String | Array)): ServerResponse
Parameters
field `(String)`
val `((String | Array))`
Returns
`ServerResponse`: for chaining
▸ set

Set header `field` to `val`, or pass an object of header fields.

Examples:

res.set('Foo', ['bar', 'baz']); res.set('Accept', 'application/json'); res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });

Aliased as `res.header()`.

set
Parameters
field `((String | Object))`
val `((String | Array))`
Returns
`ServerResponse`: for chaining
▸ get(field)

Get value for header `field`.

get(field: String): String
Parameters
field `(String)`
Returns
`String`:
▸ clearCookie(name, options?)

Clear cookie `name`.

clearCookie(name: String, options: Object?): ServerResponse
Parameters
name `(String)`
options `(Object?)`
Returns
`ServerResponse`: for chaining
▸ cookie(name, value, options?)

Set cookie `name` to `value`, with the given `options`.

Options:

- `maxAge` max-age in milliseconds, converted to `expires`
- `signed` sign the cookie
- `path` defaults to "/"

Examples:

// "Remember Me" for 15 minutes res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });

// save as above res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })

cookie(name: String, value: (String | Object), options: Object?): ServerResponse
Parameters
name `(String)`
value `((String | Object))`
options `(Object?)`
Returns
`ServerResponse`: for chaining
▸ location(url)

Set the location header to `url`.

The given `url` can also be "back", which redirects to the Referrer or Referer headers or "/".

Examples:

res.location('/foo/bar').; res.location('http://example.com'); res.location('../login');

location(url: String): ServerResponse
Parameters
url `(String)`
Returns
`ServerResponse`: for chaining
▸ redirect(url)

Redirect to the given `url` with optional response `status` defaulting to 302.

The resulting `url` is determined by `res.location()`, so it will play nicely with mounted apps, relative paths, `"back"` etc.

Examples:

res.redirect('/foo/bar'); res.redirect('http://example.com'); res.redirect(301, 'http://example.com'); res.redirect('../login'); // /blog/post/1 -> /blog/login

redirect(url: any)
Parameters
url `(any)`
▸ vary(field)

Add `field` to Vary. If already present in the Vary set, then this call is simply ignored.

vary(field: (Array | String)): ServerResponse
Parameters
field `((Array | String))`
Returns
`ServerResponse`: for chaining
▸ render(view, options, callback)

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

Options:

- `cache` boolean hinting to the engine it should cache
- `filename` filename of the view being rendered

render(view: any, options: any, callback: any)
Parameters
view `(any)`
options `(any)`
callback `(any)`

### morgan

Create a logger middleware.

morgan(format: (String | Function), options: Object?): Function
Parameters
format `((String | Function))`
options `(Object?)`
Returns
`Function`: middleware

### format

Define a format with the given name.

format(name: string, fmt: (string | function))
Parameters
name `(string)`
fmt `((string | function))`

### token

Define a token function with the given name, and callback fn(req, res).

token(name: string, fn: function)
Parameters
name `(string)`
fn `(function)`

### compile

Compile a format string into a function.

compile(format: string): function
Parameters
format `(string)`
Returns
`function`:

### createBufferStream

Create a basic buffering stream.

createBufferStream(stream: object, interval: number)
Parameters
stream `(object)`
interval `(number)`

### getFormatFunction

Lookup and compile a named format function.

getFormatFunction(name: string): function
Parameters
name `(string)`
Returns
`function`:

### defineProperty

JSON parser.

defineProperty

### defineProperty

Raw parser.

defineProperty

### defineProperty

Text parser.

defineProperty

### defineProperty

URL-encoded parser.

defineProperty

### json

Create a middleware to parse JSON bodies.

json(options: object?): function
Parameters
options `(object?)`
Returns
`function`:

### urlencoded

Create a middleware to parse urlencoded bodies.

urlencoded(options: object?): function
Parameters
options `(object?)`
Returns
`function`: