Spanish Total.js
English
Documentation For AI agents
Contents

Controller

Properties and methods of the controller $ that every route action receives.

.md GitHub
On this page

The controller is the $ argument of every route action. It holds the request data ($.params, $.query, $.body, $.files, $.headers, $.user...) and the methods that send the response ($.json(), $.success(), $.invalid(), $.view(), $.file(), $.redirect()...). For a walkthrough with examples, read the guide Controller.

API

property

$.req

The Node.js request object.

Returns IncomingMessage

The http.IncomingMessage of the request. Use it only for what the controller does not offer.

property

$.res

The Node.js response object.

Returns ServerResponse

The http.ServerResponse of the request. When you write to it yourself, call $.custom() first so the framework does not answer the request too.

property

$.method

The HTTP method of the request.

Returns String

An upper-case string such as GET, POST, PUT, PATCH or DELETE.

Example
ROUTE('POST /api/items/', function($) {
	// $.method === 'POST'
	$.success();
});
property

$.url

The path of the URL.

Returns String

The path without the query string. A path without a file extension always ends with /, and double slashes are merged. The letters keep their case.

Example
ROUTE('GET /docs/', function($) {
	// /docs?page=1 gives '/docs/'
	$.plain($.url);
});
property

$.uri

The parsed URL.

Returns Object

An object with pathname (the same as $.url), search (the query string without ?), split (the segments), ext (the file extension) and file (true for a request of a static file).

property

$.split

The segments of the path.

Returns String[]

An array of the parts of the path: /blog/2025/hello/ gives ['blog', '2025', 'hello']. The root path / gives an empty array.

Example
ROUTE('GET /blog/*', function($) {
	$.json($.split);
});
property

$.params

The dynamic parts of the URL.

Returns Object

Each {name} of the route becomes a key with the matching segment of the path as a string. Convert numbers and dates yourself.

Example
exports.install = function() {
	ROUTE('GET /orders/{id}/', order);
};

function order($) {
	var id = $.params.id;
	$.json({ id: id });
}
property

$.query

The query string as an object.

Returns Object

Values are strings: ?page=2&q=shoes gives { page: '2', q: 'shoes' }. You can assign a new object. In an API route, it contains the query of the schema field.

Paging
function list($) {
	var page = ($.query.page || '1').parseInt();
	$.json({ page: page });
}
property

$.body

The parsed body of the request.

Returns Object

For POST, PUT, PATCH and DELETE requests. A JSON body is parsed into an object, a URL-encoded form into an object of strings, and a multipart/form-data request gives the fields of the form. Other content types keep {} and the raw data is in $.payload. In an API route, it contains the data of the request.

Read the body
exports.install = function() {
	ROUTE('POST /api/contact/', contact);
};

function contact($) {
	var email = $.body.email;
	$.success();
}
property

$.payload

The raw body as a Buffer.

Returns Buffer

The bytes of the body for every content type except multipart/form-data. Use it for XML, plain text or binary uploads. It is released when the response ends.

Example
ROUTE('POST /api/xml/', function($) {
	var xml = $.payload.toString('utf8');
	$.plain('Received ' + xml.length + ' chars');
});
property

$.files

The uploaded files.

Returns HttpFile[]

An array of files (HttpFile) from a multipart/form-data request, empty for other requests. The files are temporary and are removed when the response ends, unless you move them or call $.autoclear(false).

Example
function upload($) {
	var names = [];
	for (var file of $.files)
		names.push(file.filename + ' (' + file.size + ' bytes)');
	$.json(names);
}
property

$.headers

The request headers.

Returns Object

The headers object of Node.js: names are in lower case.

Example
function info($) {
	$.json({ agent: $.headers['user-agent'], lang: $.headers['accept-language'] });
}
property

$.ip

The IP address of the client.

Returns String

The first address of X-Forwarded-For when the header exists (behind a proxy), otherwise the remote address of the connection.

Example
function track($) {
	console.log('Request from', $.ip);
	$.success();
}
property

$.ua

A short name of the client from the User-Agent header.

Returns String

The system and the browser found in User-Agent, for example Mac OS Chrome, or an empty string without the header.

property

$.mobile

true for a mobile device.

Returns Boolean

true when User-Agent matches a phone or a tablet (Android, iPhone, iPad, Mobile, Tablet...).

property

$.robot

true for a crawler.

Returns Boolean

true when User-Agent contains search, agent, bot, crawler or spider.

property

$.xhr

true for an XMLHttpRequest.

Returns Boolean

true when the request has the header X-Requested-With: XMLHttpRequest. $.fallback() answers such requests with JSON instead of an HTML page.

property

$.protocol

The protocol of the request.

Returns String

https for an encrypted connection or when a proxy says so (X-Forwarded-Proto: https, X-Forwarded-SSL: on or X-Forwarded-Port: 443), otherwise http.

property

$.address

The full URL of the request.

Returns String

The protocol, the host and the original URL with the query string, for example https://example.com/products/?page=2.

property

$.user

The signed-in user.

Returns Object

The object your authorization delegate returned for the request, or undefined when nobody is signed in. See Authorization.

Example
ROUTE('+GET /api/account/', function($) {
	$.json({ name: $.user.name });
});
property

$.language

The language of the request.

Returns String

The value your localization delegate returned, or an empty string. It selects the translation of views and of error messages. See Localization.

property

$.response

The response that will be sent.

Returns Object

An object with status (default 200), headers (an object of response headers), cache (HTTP cache for files) and minify. Change it before you call a response method.

Status and a header
function create($) {
	$.response.status = 201;
	$.response.headers['x-version'] = '1';
	$.json({ id: UID() });
}
method

$.json(value, [beautify], [replacer])

Sends JSON.
ParameterTypeDescription
value Object The value to serialize.
beautify? Boolean true indents the JSON with tabs. Default: false
replacer? Function|Array A replacer for JSON.stringify().

Serializes value with JSON.stringify(), sets content-type: application/json and headers that disable caching (cache-control: private, no-cache, no-store, max-age=0, expires: -1). beautify indents the output with tabs. replacer is passed to JSON.stringify() as its second argument: a function (key, value) or an array of keys to keep.

Example
ROUTE('GET /api/products/', function($) {
	$.json([{ id: 1, name: 'Shoes' }]);
});
Beautify and hide a key
ROUTE('GET /api/debug/', function($) {
	$.json({ id: 1, password: 'secret' }, true, function(key, value) {
		return key === 'password' ? undefined : value;
	});
});
method

$.jsonstring(value)

Sends a string that is already JSON.
ParameterTypeDescription
value String A JSON string.

Sends the string as it is with the same headers as $.json(). Use it for JSON you have cached or read from a file.

Example
function cached($) {
	$.jsonstring('{"ok":true}');
}
method

$.success([value])

Sends { success: true, value: value }.
ParameterTypeDescription
value? Object An optional value for the value key.

A shortcut for the usual answer of an API. Without value the response is {"success":true}.

Example
function remove($) {
	NOSQL('products').remove().id($.params.id);
	$.success($.params.id);
}
method

$.invalid(error)

Sends an error as JSON.
ParameterTypeDescription
error String|Error|ErrorBuilder|Number The error.

Accepts a string, an Error, an ErrorBuilder or an HTTP status code. The response is a JSON array such as [{"error":"Name is required"}] with the status 400, or the given status code ($.invalid(404) gives [{"error":"404: Not Found"}] with status 404). Text written as @(text) is translated from a resource. Without an argument it sends 401. The response is sent asynchronously.

Example
function save($) {
	if (!$.body.email) {
		$.invalid('@(Email is required)');
		return;
	}
	$.success();
}
method

$.invalidsafe(message, [error])

Sends an error message and logs the real error.
ParameterTypeDescription
message String|Number|ErrorBuilder The error for the client.
error? Error|String The error for the log.

Sends message as $.invalid(message) does and writes error to the error log with F.error() and the URL of the request. The client gets only the message. message can also be an ErrorBuilder.

Example
function report($) {
	F.Fs.readFile(PATH.root('reports/2025.csv'), function(err, buffer) {
		if (err)
			$.invalidsafe('The report is not available', err);
		else
			$.content(buffer, 'text/csv');
	});
}
method

$.html(value)

Sends HTML.
ParameterTypeDescription
value String HTML.

Sets content-type: text/html and sends the string. It is minified when the configuration key $minifyhtml is true (the default).

Example
ROUTE('GET /hello/', function($) {
	$.html('<h1>Hello</h1>');
});
method

$.throw(error)

Writes an error to the log.
ParameterTypeDescription
error Error|String The error.

Returns Controller The same controller.

Passes error with the URL of the request to the error handler of the framework (DEF.onError): it is printed, kept in F.errors and emitted as the error event. Nothing is sent to the client. Returns $.

Example
function save($) {
	NOSQL('visits').insert({ url: $.url, dtcreated: NOW }).callback(function(err) {
		err && $.throw(err);
	});
	$.success();
}
method

$.plain(value)

Sends plain text.
ParameterTypeDescription
value String The text.

Sets content-type: text/plain. $.text() is the same method.

Example
ROUTE('FILE /robots.txt', function($) {
	$.plain('User-agent: *');
});
method

$.xml(value)

Sends XML.
ParameterTypeDescription
value String XML.

Sets content-type: text/xml and sends the string.

Example
function feed($) {
	$.xml('<?xml version="1.0"?><rss></rss>');
}
method

$.empty()

Sends status 204 without a body.

Use it when a request needs no data in the answer.

Example
ROUTE('POST /api/ping/', function($) {
	$.empty();
});
method

$.redirect(url, [permanent])

Redirects the client.
ParameterTypeDescription
url String The target URL.
permanent? Boolean true for a permanent redirect (301). Default: false

Sets the Location header and the status 302, or 301 when permanent is true.

Example
ROUTE('GET /old/', function($) {
	$.redirect('/new/', true);
});
method

$.view([name], [model])

Renders a view and sends it as HTML.
ParameterTypeDescription
name? String The name of the view, without the extension.
model? Object The model for the view.

Returns View The view instance.

Renders the view name from the /views/ directory with model and sends it with $.html(). With the layout from $.layout(). Without name it only returns a new View instance for the controller. See Views.

Example
function detail($) {
	NOSQL('products').one().id($.params.id).callback(function(err, response) {
		if (response)
			$.view('detail', response);
		else
			$.fallback(404);
	});
}
method

$.layout(name)

Chooses the layout for the next view.
ParameterTypeDescription
name String The name of the layout view.

The view rendered with $.view() is placed into the layout name.

Example
function admin($) {
	$.layout('layout-admin');
	$.view('dashboard');
}
method

$.file(path, [download])

Sends a file from the disk.
ParameterTypeDescription
path String An absolute path of the file.
download? Boolean|String A file name for the download, or true.

Sets the content type from the extension and supports Range requests, gzip and HTTP cache headers. JS, CSS and HTML files are minified unless their name contains .min, -min or @min. With download the browser saves the file: pass true to keep its name or a string to rename it. A missing file gives 404.

Example
ROUTE('GET /download/', function($) {
	$.file(PATH.root('reports/2025.pdf'), 'report.pdf');
});
method

$.stream(type, stream, [download])

Sends a readable stream.
ParameterTypeDescription
type String The content type.
stream ReadableStream The stream.
download? String A file name for the download.

Pipes stream to the response with the content type type (default application/octet-stream). Text types are compressed with gzip when the client supports it. A string download sends the stream as an attachment with that name.

Example
function exportcsv($) {
	var stream = F.Fs.createReadStream(PATH.root('export.csv'));
	$.stream('text/csv', stream, 'export.csv');
}
method

$.binary(buffer, type, [download])

Sends a Buffer.
ParameterTypeDescription
buffer Buffer The data.
type String The content type.
download? String A file name for the download.

Sends the bytes with the content type type. A string download sends them as an attachment with that name.

Example
function pixel($) {
	var buffer = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');
	$.binary(buffer, 'image/gif');
}
method

$.content(value, [type])

Sends a string or a Buffer with a content type.
ParameterTypeDescription
value String|Buffer The content.
type? String The content type. Default: 'application/octet-stream'

Sends value with the header content-type: type; without type it is application/octet-stream. A string is sent as UTF-8. Unlike $.binary(), it takes a string too and has no download name.

CSV
ROUTE('GET /export/', function($) {
	$.content('id,name\n1,Mug\n', 'text/csv');
});
method

$.image(opt)

Processes an image and sends it.
ParameterTypeDescription
opt Object The options.

Loads an image stream, lets you change it and sends the result. opt.ext (required) is the extension of the output, opt.load(next, opt) calls next(stream) with the source, opt.image(img, opt) changes the image (see Images), opt.cache is a key to keep the result in the temporary directory, and opt.date a date for the HTTP cache.

Example
function thumbnail($) {
	$.image({
		ext: 'jpg',
		cache: 'thumb_' + $.params.id,
		load: function(next) {
			next(F.Fs.createReadStream(PATH.public('photos/' + $.params.id + '.jpg')));
		},
		image: function(img) {
			img.resize(200, 200);
		}
	});
}
method

$.filefs(name, id, [download], [checkmeta])

Sends a file from a file storage.
ParameterTypeDescription
name String The name of the file storage.
id String The identifier of the file.
download? Boolean|String Send as an attachment.
checkmeta? Function A check of the metadata.

Returns Object The options passed to the storage.

Sends the file id from the file storage name (see File storage). download sends it as an attachment, true with its stored name or a string for another name. checkmeta is a function that receives the metadata of the file and decides whether it can be sent.

Example
ROUTE('GET /files/{id}/', function($) {
	$.filefs('files', $.params.id);
});
method

$.proxy(opt)

Forwards the request to another server.
ParameterTypeDescription
opt String|Object The target URL or options.

Sends the method, the headers, the body and the query string of the request to opt (a URL, or an object with url, method, headers, timeout (default 10000 ms) and callback(err, response)) and answers with the response of that server.

Example
ROUTE('GET /api/weather/', function($) {
	$.proxy('https://weather.example.com/today/');
});
method

$.fallback(code, [error])

Sends an error page.
ParameterTypeDescription
code Number The HTTP status code.
error? String|Error The error for debug mode.

When a route #code exists (for example ROUTE('#404', fn)), its action handles the request; the status stays 200 unless the action sets $.response.status. Otherwise it sends the built-in error page with the status code, or $.invalid(code) for XHR requests. error is shown on the page in debug mode.

Example
exports.install = function() {
	ROUTE('GET /secret/', function($) {
		$.fallback(404);
	});
	ROUTE('#404', function($) {
		$.view('404');
	});
};
method

$.callback([err], [value])

Answers from a callback.
ParameterTypeDescription
err? Error An error.
value? Object The value to send.

Returns Function A callback when called without arguments.

Without arguments it returns a function (err, response) that calls $.invalid(err) or $.json(response). With arguments it answers at once: $.invalid(err), $.success() when value is undefined, or $.json(value).

Example
ROUTE('GET /api/products/', function($) {
	NOSQL('products').find().callback($.callback());
});
method

$.done([value])

Returns a callback that answers with success.
ParameterTypeDescription
value? Object|Boolean The value, or true for the response of the callback.

Returns Function A callback.

The returned function (err, response) calls $.invalid(err) on an error, otherwise sends { success: true, value: value }. Pass true to use the response of the callback as the value.

Example
ROUTE('POST /api/products/', function($) {
	NOSQL('products').insert($.body).callback($.done(true));
});
method

$.successful(callback)

Returns a callback that handles errors for you.
ParameterTypeDescription
callback Function Called when there is no error.

Returns Function A callback.

The returned function (err, a, b, c) calls $.invalid(err) on an error, otherwise callback(a, b, c) with the controller as this.

Example
ROUTE('GET /api/products/', function($) {
	NOSQL('products').find().callback($.successful(function(response) {
		$.json(response);
	}));
});
method

$.custom()

Tells the framework you send the response yourself.

Marks the controller as finished so that no response method writes to it. Then write to $.res with the Node.js API.

Example
ROUTE('GET /events/', function($) {
	$.custom();
	$.res.writeHead(200, { 'content-type': 'text/event-stream' });
	$.res.write('data: hello\n\n');
});
method

$.cookie(name, [value], [expires], [options])

Reads or sets a cookie.
ParameterTypeDescription
name String The name of the cookie.
value? String The value to set.
expires? Date|String|Object The expiration, or the options.
options? Object The options of the cookie.

Returns String|Controller The value when reading, the controller when setting.

With only name it returns the decoded value of the cookie, or an empty string. With value it adds a Set-Cookie header (a cookie with the same name set earlier in the request is replaced) and returns the controller. expires is a Date, a string such as '7 days', or the options object. The options are expires, domain, path (default /), secure (default from $cookiesecure), httponly and samesite (default from $cookiesamesite, 'Lax').

Example
function login($) {
	$.cookie('session', 'abc123', '7 days', { httponly: true, samesite: 'Strict' });
	$.success();
}

function profile($) {
	$.json({ session: $.cookie('session') });
}
method

$.httpcache(date)

Sets the HTTP cache headers.
ParameterTypeDescription
date Date|String The date of the last change.

Sets Last-Modified to date, ETag, and Expires and Cache-Control when they are not set yet.

Example
function article($) {
	var updated = new Date(2025, 0, 1);
	if ($.notmodified(updated.toUTCString()))
		return;
	$.httpcache(updated);
	$.view('article');
}
method

$.notmodified(date)

Answers 304 when the client has the same version.
ParameterTypeDescription
date String The date of the last change as a UTC string.

Returns Boolean true when the 304 response was sent.

Compares date (a UTC string) with the If-Modified-Since header. When they are equal it sends 304 Not Modified and returns true.

method

$.hostname([path])

Returns the protocol and the host.
ParameterTypeDescription
path? String A path to append.

Returns String The URL.

Gives protocol://host of the request with an optional path appended.

Example
function share($) {
	$.json({ url: $.hostname('/products/' + $.params.id + '/') });
}
method

$.href([key], [value])

Returns the query string with one parameter changed.
ParameterTypeDescription
key? String|Object The name of the parameter, or an object with the parameters to set.
value? String|Number|Array|Object The new value.

Returns String The query string with ?, or an empty string.

Without arguments it returns the query string of the request (?page=2&sort=name), or an empty string. $.href(key, value) returns it with key set to value; the other parameters stay. Without value the current value of key is kept. More arguments after value are names of parameters to remove. An array value writes the parameter once for each item and an object value is written as JSON. $.href({ key: value, ... }) returns the URL of the request with the query string changed by the keys of the object. It works like @{href()} in views.

Paging
// GET /products/?page=2&sort=name
function products($) {
	$.json({
		next: $.href('page', 3),           // ?page=3&sort=name
		current: $.href()                  // ?page=2&sort=name
	});
}
Remove a parameter, or change several
// GET /products/?page=2&sort=name&q=pen
$.href('page', 1, 'sort');           // ?page=1&q=pen
$.href({ page: 1, sort: 'price' });  // /products/?page=1&sort=price&q=pen
method

$.touch([url])

Clears the cached state of a static file.
ParameterTypeDescription
url? String The URL of the file. Default: $.url

Returns Controller The same controller.

Calls TOUCH(url); without url it uses the URL of the request. Use it after the route changes a file in public/. Returns $.

Example
ROUTE('POST /api/theme/', function($) {
	F.Fs.writeFile(PATH.public('css/theme.css'), $.body.css || '', function(err) {
		if (err) {
			$.invalidsafe('The theme can\'t be saved', err);
			return;
		}
		$.touch('/css/theme.css');
		$.success();
	});
});
method

$.action(name, model)

Runs an action with this controller.
ParameterTypeDescription
name String The name of the action, for example Products/list.
model Object The data for the action.

Returns Object The action instance.

Calls the action name (see Actions) with model and the controller. Call .autorespond() on the result to answer the request with the output of the action.

Example
ROUTE('POST /api/orders/', function($) {
	$.action('Orders/create', $.body).autorespond();
});
method

$.authorize([callback])

Runs the authorization delegate manually.
ParameterTypeDescription
callback? Function Receives (err, user).

Returns Promise When called without a callback.

Calls your authorization delegate for this request. When it returns a user, $.user is set. The callback is (err, user); without a callback the method returns a Promise with the user (or undefined).

Example
ROUTE('GET /api/me/', async function($) {
	var user = await $.authorize();
	$.json({ signed: !!user });
});
method

$.csrf()

Creates a CSRF token.

Returns String The token.

Returns a token bound to the IP address and the browser of the client, valid for the time in $csrfexpiration (default 30 minutes). It needs the configuration key secret_csrf; without it the token is an empty string.

Example
ROUTE('GET /form/', function($) {
	$.view('form', { token: $.csrf() });
});
method

$.autoclear([value])

Keeps or removes uploaded files after the response.
ParameterTypeDescription
value? Boolean false keeps the files.

Uploaded files are removed when the response ends. $.autoclear(false) keeps them, for example when you process them later.

method

$.cancel()

Stops the processing of the request in an event.

Call it in ON('request', fn) or ON('controller', fn) when the handler answers the request itself.

Example
ON('request', function($) {
	if ($.url === '/health/') {
		$.cancel();
		$.plain('OK');
	}
});
class

HttpFile

An uploaded file in $.files.

Properties: name (the field of the form), filename, type (the content type), size (bytes), extension, width and height (images), path (the temporary file), and isImage, isVideo, isAudio.

Methods:

  • move(filename, [callback]) (also rename()) moves the file; without a callback it returns a Promise. A moved file is not removed after the response.
  • copy(filename, callback) copies the file.
  • read([callback]) reads the file into a Buffer; without a callback it returns a Promise.
  • md5([callback]) computes the MD5 hash in hex; without a callback it returns a Promise.
  • stream([opt]) returns a read stream; pipe(stream, [opt]) pipes the file into a stream.
  • image([shell]) returns an image object for Images.
  • fs(storage, id, [callback]) saves the file into a file storage.
Save to a file storage
ROUTE('POST /upload/ <10MB', function($) {
	var file = $.files[0];
	file.fs('files', UID(), function(err, meta) {
		if (err)
			$.invalid(err);
		else
			$.success(meta.id);
	});
});
Made in Europe