Utilities
The functions of U (utils.js) and the global helpers and objects of the framework.
On this page
Total.js defines helpers in the global scope and in the object U (Utils), so every file of an app can use them without require(). The guide Utilities explains how to use them with examples; this page is the exact reference.
API
property
U
The utility library of the framework (utils.js).
UReturns Object
U, Utils and utils are the same object. It is global, so you use it in controllers, schemas, modules and plugins without require().
var ext = U.getExtension('photo.JPG'); // 'jpg'
property
Total
since 0.0.96
A global alias of the framework instance F.
TotalReturns Framework
Total, F and framework refer to the same object.
console.log(Total === F); // true
property
NOW
A Date that the framework refreshes regularly.
NOWReturns Date
Reading NOW is cheaper than new Date(). The framework sets it again in its internal intervals (about every minute) and in some calls, such as LOGGER(). Use it where a precision of a minute is enough; use new Date() for an exact time. F.datetime reads and writes the same value.
var model = { id: UID(), dtcreated: NOW };
property
EMPTYOBJECT
A frozen empty object.
EMPTYOBJECTReturns Object
Use it as a default value that is never modified. It is frozen, so assignments to it have no effect.
function send(options) {
options = options || EMPTYOBJECT;
return options.timeout || 5000;
}
property
EMPTYARRAY
A frozen empty array.
EMPTYARRAYReturns Array
Use it as a default value that is never modified. It is frozen, so push() throws an error.
var items = response.items || EMPTYARRAY;
method
NOOP()
An empty function.
NOOP()Returns undefined
Pass it where a callback is required and you do not need the result.
Fs.unlink(PATH.temp('export.csv'), NOOP);
property
MAIN
An empty global object for your own shared data.
MAINReturns Object
The framework creates MAIN = {} and does not use it. Store application-wide values in it, for example data loaded at start.
// definitions/init.js
MAIN.settings = { currency: 'EUR' };
// any other file
var currency = MAIN.settings.currency;
property
REPO
An empty global object for your own repository of values.
REPOReturns Object
The framework creates REPO = {} and does not use it. It is a second namespace like MAIN.
REPO.countries = ['SK', 'CZ', 'AT'];
property
FUNC
An empty global object for your own shared functions.
FUNCReturns Object
The framework creates FUNC = {}. Put helpers there that several files of the app call.
// definitions/func.js
FUNC.price = function(value) {
return value.format(2) + ' EUR';
};
// a controller or a schema
var text = FUNC.price(12.5);
property
TEMP
A global object for temporary data that the framework clears.
TEMPReturns Object
The framework replaces TEMP with a new empty object in its periodic cleanup (every CONF.default_interval_clear_cache minutes, 10 by default). Do not keep anything there that you need later.
if (!TEMP.stats)
TEMP.stats = compute();
property
MODS
All loaded modules by their name.
MODSReturns Object
The same object as F.modules. A key is the name of the file in /modules/ (or the id the module exports).
Object.keys(MODS).forEach(function(name) {
console.log(name);
});
method
MODULE(name)
Returns a loaded module.
MODULE(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the module. |
Returns Object The module, or null.
Reads F.modules[name]. The result is the exports of the module file, or null when no module of that name is loaded.
// modules/mailer.js
exports.send = function(email) { /* ... */ };
// anywhere
MODULE('mailer').send('info@example.com');
method
LOGGER(name, value1, [value2], [...])
Appends a line to a log file in the /logs/ directory.
LOGGER(name, value1, [value2], [...])| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the log file without .log. |
value |
Object |
One or more values to write. |
Returns undefined
The line is yyyy-MM-dd HH:mm:ss | values in the file {name}.log. Values are separated by a space; objects are formatted with util.inspect(). The directory is created when it does not exist, and writes go through U.queue() with at most 5 writes at the same time.
LOGGER('payments', 'order', order.id, 'paid', order.price);
// logs/payments.log:
// 2021-03-01 10:22:05 | order 1a2b3c paid 39.9
method
PROMISIFY(fn, [a], [b], [c])
since 0.0.97
Calls a callback-style function and returns a Promise.
PROMISIFY(fn, [a], [b], [c])| Parameter | Type | Description |
|---|---|---|
fn |
Function |
A function that takes a callback as its last argument. |
a? |
Object |
First argument. |
b? |
Object |
Second argument. |
c? |
Object |
Third argument. |
Returns Promise
fn is called with the given arguments and a callback function(err, response) as the last argument. The Promise rejects with err or resolves with response. Up to three arguments are supported; arguments that are undefined are not passed.
var Fs = require('fs');
var content = await PROMISIFY(Fs.readFile, PATH.root('readme.md'), 'utf8');
function load(id, callback) {
callback(null, { id: id });
}
var item = await PROMISIFY(load, '123');
method
WAIT(validator, callback, [timeout], [interval])
Waits until a condition is true.
WAIT(validator, callback, [timeout], [interval])| Parameter | Type | Description |
|---|---|---|
validator |
Function |
Returns true when the wait is over. |
callback |
Function |
function(err, success). |
timeout? |
Number |
Maximum time in ms. Default: 5000 |
interval? |
Number |
Time between checks in ms. Default: 500 |
Returns undefined
validator() is checked at once and then every interval ms. When it returns true, callback(null, true) is called. When timeout ms pass first, callback(Error('Timeout'), false) is called.
WAIT(function() {
return MAIN.db != null;
}, function(err) {
if (err)
console.log('Database is not ready');
else
console.log('Ready');
}, 10000);
method
UID([type], [date])
Creates a short unique identifier.
UID([type], [date])| Parameter | Type | Description |
|---|---|---|
type? |
String |
A name of an independent counter. |
date? |
Date |
The time encoded in the ID. Default: NOW |
Returns String
The ID is a time-based string, for example 24j0y001xn51d, which sorts by the time it was created. It is unique within the running instance (the framework adds a random instance key). type keeps a separate counter for each type, so IDs of different collections do not share a sequence. date creates the ID for another time. CONF.default_uid selects the version: r gives a random ID (UIDR()), f a base-62 variant; the default is the d version.
var model = {};
model.id = UID();
model.dtcreated = NOW;
var orderid = UID('orders');
var invoiceid = UID('invoices');
method
UID16([type], [date])
Creates a unique identifier with the time part in base 16.
UID16([type], [date])| Parameter | Type | Description |
|---|---|---|
type? |
String |
A name of an independent counter. |
date? |
Date |
The time encoded in the ID. Default: NOW |
Returns String
Works like UID() but encodes the time in hexadecimal, so the ID is a little longer (version c). It ignores CONF.default_uid.
var id = UID16(); // e.g. '367b52002xn60c'
method
GUID([length])
Creates a GUID or a random string of a given length.
GUID([length])| Parameter | Type | Description |
|---|---|---|
length? |
Number |
Length of a random string. |
Returns String
Without length it returns a string in the UUID form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx built from the current time and random numbers. With length it returns random lowercase letters and digits of that length. Also available as U.GUID().
var id = GUID(); // '1a1defc8-efc8-2c86-8d36-938350b51dfd'
var token = GUID(30);
method
CLONE(obj, [skip], [skipFunctions])
Creates a deep copy of an object or an array.
CLONE(obj, [skip], [skipFunctions])| Parameter | Type | Description |
|---|---|---|
obj |
Object |
The object or array to copy. |
skip? |
Object |
Keys to leave out, as { key: true }. |
skipFunctions? |
Boolean |
Leaves out functions. Default: false |
Returns Object A new object.
Nested objects and arrays are copied; Date and Error values are kept by reference, and Buffers are copied. skip is an object of keys to leave out ({ password: 1 }) on the first level of objects. Also available as U.clone().
var copy = CLONE(user, { password: 1 });
copy.name = 'Peter'; // user.name is unchanged
method
COPY(source, [target])
Copies all properties of source to target.
COPY(source, [target])| Parameter | Type | Description |
|---|---|---|
source |
Object |
Object to read. |
target? |
Object |
Object to write. |
Returns Object The target.
Every key of source is cloned into target, also keys that target does not have. Without target it returns a new copy of source. It is U.copy(source, target, true).
var target = { a: 0 };
COPY({ a: 1, z: 9 }, target);
// target: { a: 1, z: 9 }
method
HASH(value, [type])
Creates a hash of a string.
HASH(value, [type])| Parameter | Type | Description |
|---|---|---|
value |
String |
The text. |
type? |
String |
A hash algorithm. |
Returns Number|String
Without type it returns a fast numeric hash (unsigned 32-bit). type can be md5, sha1, sha256, sha512, crc32 or crc32unsigned. It calls value.hash().
HASH('abc'); // 96354
HASH('abc', 'md5'); // '900150983cd24fb0d6963f7d28e17f72'
method
QUERIFY([url], obj)
Adds an object to a URL as a query string.
QUERIFY([url], obj)| Parameter | Type | Description |
|---|---|---|
url? |
String |
The URL. |
obj |
Object |
Values of the query string. |
Returns String
Values that are null or undefined are left out; dates become ISO strings and arrays are joined with commas. Keys and values are encoded. The URL can start with a method (GET /api/); the query is added to the path. Without a URL it returns only ?key=value.
QUERIFY('GET /api/products/', { page: 2, q: 'a b' });
// 'GET /api/products/?page=2&q=a%20b'
QUERIFY({ page: 1 }); // '?page=1'
method
DIFFARR(prop, db, form)
Compares two arrays of objects by a key.
DIFFARR(prop, db, form)| Parameter | Type | Description |
|---|---|---|
prop |
String |
Name of the key, for example id. |
db |
Object[] |
The stored items. |
form |
Object[] |
The new items. |
Returns Object { add: [], upd: [], rem: [] }
Returns { add, upd, rem }: add holds items of form that are not in db, upd holds { db, form } pairs that exist in both, and rem holds the key values of items of db that are missing in form. Use it to save a list that a user edited.
var diff = DIFFARR('id', [{ id: 1 }, { id: 2 }], [{ id: 2, name: 'B' }, { id: 3 }]);
// diff.add: [{ id: 3 }]
// diff.upd: [{ db: { id: 2 }, form: { id: 2, name: 'B' } }]
// diff.rem: [1]
method
PATH.root([filename])
Returns a path in the root directory of the app.
PATH.root([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A relative path. |
Returns String
The result always uses / as the separator.
var filename = PATH.root('data/countries.json');
method
PATH.temp([filename])
Returns a path in the temporary directory and creates the directory.
PATH.temp([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String
The directory is CONF.directory_temp. PATH.tmp() and PATH.temporary() are aliases.
var filename = PATH.temp('export-' + UID() + '.csv');
method
PATH.databases([filename])
Returns a path in the databases directory and creates the directory.
PATH.databases([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String
The directory is CONF.directory_databases.
var filename = PATH.databases('settings.json');
method
PATH.logs([filename])
Returns a path in the logs directory and creates the directory.
PATH.logs([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String
The directory is CONF.directory_logs. LOGGER() writes there.
require('fs').readFile(PATH.logs('payments.log'), 'utf8', function(err, text) {
console.log(text);
});
method
PATH.mkdir(path, [cache])
Creates a directory with all missing parent directories.
PATH.mkdir(path, [cache])| Parameter | Type | Description |
|---|---|---|
path |
String |
An absolute path. |
cache? |
Boolean |
Skips paths created before. Default: false |
Returns undefined
It works synchronously. With cache set to true, a path that was already created is not checked again until the framework clears its cache.
var dir = PATH.databases('uploads/2021/');
PATH.mkdir(dir, true);
method
U.random([max], [min])
Returns a random integer between min and max, both included.
U.random([max], [min])| Parameter | Type | Description |
|---|---|---|
max? |
Number |
The highest value. Default: 100000 |
min? |
Number |
The lowest value. Default: 0 |
Returns Number
var dice = U.random(6, 1);
method
U.random_text(length)
Returns a random string of letters and digits.
U.random_text(length)| Parameter | Type | Description |
|---|---|---|
length |
Number |
Number of characters. |
Returns String
Characters are 0-9, A-Z and a-z.
var code = U.random_text(8); // e.g. '1qrWGUa7'
method
U.random_string(length)
Returns a random string of letters.
U.random_string(length)| Parameter | Type | Description |
|---|---|---|
length |
Number |
Number of characters. |
Returns String
Characters are A-Z and a-z, without digits.
var name = U.random_string(6);
method
U.random_number(length)
Returns a string of random digits.
U.random_number(length)| Parameter | Type | Description |
|---|---|---|
length |
Number |
Number of digits. |
Returns String
The first digit is never 0, so +value has the same number of digits. The result is a string.
var pin = U.random_number(6); // e.g. '986081'
method
U.encrypt_uid(value, [key])
Signs an ID so that it cannot be changed by the client.
U.encrypt_uid(value, [key])| Parameter | Type | Description |
|---|---|---|
value |
String|Number |
The ID. |
key? |
String |
A secret key. Default: CONF.secret |
Returns String
The result contains the ID and a checksum of the ID and the key, for example n3ck9tg6x123. The value is not hidden; it is protected against changes. Use U.decrypt_uid() to read it back.
var link = '/download/' + U.encrypt_uid(file.id) + '/';
method
U.decrypt_uid(value, [key])
Reads an ID signed by U.encrypt_uid().
U.decrypt_uid(value, [key])| Parameter | Type | Description |
|---|---|---|
value |
String |
The signed ID. |
key? |
String |
The secret key used to sign it. Default: CONF.secret |
Returns String|Number The ID, or null.
Returns the original ID (a number when a number was signed), or null when the checksum does not match.
var id = U.decrypt_uid(this.params.id);
if (id == null) {
this.throw404();
return;
}
method
U.copy(source, [target])
Copies the values of source to the keys that target already has.
U.copy(source, [target])| Parameter | Type | Description |
|---|---|---|
source |
Object |
Object to read. |
target? |
Object |
Object to write. |
Returns Object The target.
Only keys that exist in target (with a value other than undefined) are written; values are cloned. Without target it returns a new copy of source. To copy all keys, use COPY().
var item = { name: '', price: 0 };
U.copy({ name: 'Book', price: 9, hack: true }, item);
// item: { name: 'Book', price: 9 }
method
U.extend(target, source, [rewrite])
Adds the properties of source to target.
U.extend(target, source, [rewrite])| Parameter | Type | Description |
|---|---|---|
target |
Object |
Object to write. |
source |
Object |
Object to read. |
rewrite? |
Boolean |
Overwrites existing values. Default: true |
Returns Object The target.
Values are cloned. With rewrite set to false, keys that already have a value in target are kept, so source acts as a set of defaults.
var options = { timeout: 1000 };
U.extend(options, { timeout: 5000, retry: 3 }, false);
// options: { timeout: 1000, retry: 3 }
method
U.reduce(source, props, [reverse])
Keeps only some properties of an object.
U.reduce(source, props, [reverse])| Parameter | Type | Description |
|---|---|---|
source |
Object|Object[] |
The object or array of objects. |
props |
String[]|Object |
Keys to keep. |
reverse? |
Boolean |
Removes the listed keys instead. Default: false |
Returns Object|Object[]
props is an array of keys or an object whose keys are used. With reverse set to true, the listed keys are removed instead. An array as source reduces each item. The result is a new object.
var output = U.reduce(user, ['id', 'name']);
var safe = U.reduce(user, ['password'], true);
method
U.get(obj, path)
Reads a value by a path such as address.city.
U.get(obj, path)| Parameter | Type | Description |
|---|---|---|
obj |
Object |
The object. |
path |
String |
The path with dots. |
Returns Object The value.
Returns undefined when a part of the path does not exist. Indexes are written as items[0].name. Paths that contain code-like characters (spaces, brackets of calls, __proto__ and similar) return undefined.
U.get({ address: { city: 'Bratislava' } }, 'address.city'); // 'Bratislava'
U.get({}, 'address.city'); // undefined
method
U.set(obj, path, value)
Writes a value by a path such as address.city.
U.set(obj, path, value)| Parameter | Type | Description |
|---|---|---|
obj |
Object |
The object. |
path |
String |
The path with dots. |
value |
Object |
The value. |
Returns Object The value.
Missing objects on the path are created. A path that ends with [] pushes the value to an array. Paths that contain code-like characters are ignored.
var obj = {};
U.set(obj, 'address.city', 'Bratislava');
U.set(obj, 'tags[]', 'new');
// { address: { city: 'Bratislava' }, tags: ['new'] }
method
U.trim(obj, [clean])
Trims all string values of an object or an array.
U.trim(obj, [clean])| Parameter | Type | Description |
|---|---|---|
obj |
Object|Array|String |
The value to trim. |
clean? |
Boolean |
Replaces empty strings with undefined. Default: false |
Returns Object The same value.
Nested objects and arrays are trimmed too; the object is changed in place. With clean set to true, empty strings become undefined.
U.trim({ name: ' Peter ', note: ' ' }, true);
// { name: 'Peter', note: undefined }
method
U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])
Extracts keywords from a text.
U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])| Parameter | Type | Description |
|---|---|---|
content |
String|String[] |
The text. |
forSearch? |
Boolean |
Normalizes the words for search. Default: true |
alternative? |
Boolean |
Shortens the words. Default: false |
max_count? |
Number |
Maximum number of words read. Default: 200 |
max_length? |
Number |
Longer words are skipped. Default: 20 |
min_length? |
Number |
Shorter words are skipped. Default: 2 |
Returns String[]
The text is lowercased and split into words; the result is a list of unique words, the most frequent first. With forSearch (the default), diacritics are removed and y is replaced with i, so the same words match in a search. alternative shortens each word to 80 % of its length to match word forms. content can be an array of texts.
var keywords = U.keywords(product.name + ' ' + product.description).join(' ');
method
U.queue(name, max, fn, [param])
Runs functions with a limit of how many run at the same time.
U.queue(name, max, fn, [param])| Parameter | Type | Description |
|---|---|---|
name |
String |
Name of the queue. |
max |
Number |
Maximum running functions. |
fn |
Function |
function(next, param). |
param? |
Object |
A value passed to fn. |
Returns Boolean
Each call adds fn(next, param) to the queue name. At most max functions of that queue run at once; each must call next() when it finishes. Returns true when fn starts at once, false when it waits.
urls.forEach(function(url) {
U.queue('downloads', 3, function(next, url) {
download(url, next);
}, url);
});
method
U.sortcomparer(sort)
Creates a compare function for Array.sort() from a text.
U.sortcomparer(sort)| Parameter | Type | Description |
|---|---|---|
sort |
String |
The sort definition. |
Returns Function function(a, b)
sort is a list of fields separated by commas, each with an optional _asc or _desc suffix, for example price_desc,name. Nested fields such as address.city are supported. Strings, numbers, booleans and dates are compared by their type.
products.sort(U.sortcomparer('price_desc,name_asc'));
method
U.combine(path1, [path2], [...])
Joins paths relative to the root directory of the app.
U.combine(path1, [path2], [...])| Parameter | Type | Description |
|---|---|---|
path |
String |
One or more parts of the path. |
Returns String An absolute path.
A part that starts with ~ is an absolute path and replaces what was before it. On Windows the result uses /.
U.combine('/public/', 'img'); // '/www/app/public/img'
U.combine('~/var/data/', 'file.txt'); // '/var/data/file.txt'
method
U.join(path1, [path2], [...])
Joins parts of a path with /.
U.join(path1, [path2], [...])| Parameter | Type | Description |
|---|---|---|
path |
String |
One or more parts. |
Returns String
Slashes at the start and the end of each part are removed, and the result starts with /. Empty parts are skipped.
U.join('a', '/b/', 'c'); // '/a/b/c'
method
U.getExtension(filename, [raw])
Returns the extension of a file name without the dot.
U.getExtension(filename, [raw])| Parameter | Type | Description |
|---|---|---|
filename |
String |
The file name or URL. |
raw? |
Boolean |
Keeps the original case. Default: false |
Returns String
The extension is lowercased unless raw is true. A query string after ? is ignored. Returns an empty string when there is no extension.
U.getExtension('Photo.JPG?width=200'); // 'jpg'
method
U.getName(path)
Returns the last part of a path.
U.getName(path)| Parameter | Type | Description |
|---|---|---|
path |
String |
The path. |
Returns String
Works with / and \ separators; a trailing separator is ignored.
U.getName('/www/app/public/logo.png'); // 'logo.png'
method
U.getContentType(ext)
Returns the content type (MIME type) for an extension.
U.getContentType(ext)| Parameter | Type | Description |
|---|---|---|
ext |
String |
The extension. |
Returns String
The extension can start with a dot. An unknown extension gives application/octet-stream.
U.getContentType('json'); // 'application/json'
U.getContentType(U.getExtension(filename));
method
U.setContentType(ext, type)
Registers or changes the content type of an extension.
U.setContentType(ext, type)| Parameter | Type | Description |
|---|---|---|
ext |
String |
The extension, with or without a dot. |
type |
String |
The content type. |
Returns Boolean true
The framework uses the table to serve static files, so a new extension also becomes a known static file.
// definitions/init.js
U.setContentType('gpx', 'application/gpx+xml');
method
U.ls(path, [callback], [filter], [unified])
Lists all files and directories in a directory and its subdirectories.
U.ls(path, [callback], [filter], [unified])| Parameter | Type | Description |
|---|---|---|
path |
String |
The directory. |
callback? |
Function |
function(files, directories). |
filter? |
String|RegExp|Function |
A filter. |
unified? |
Boolean |
Uses / on Windows. Default: false |
Returns Promise|undefined A Promise without a callback.
callback(files, directories) receives arrays of absolute paths. Without a callback the method returns a Promise of { files, directories }. filter is a string (part of the name, not case-sensitive), a RegExp, or function(path, isDirectory) that returns true to keep an item; the string and RegExp filters apply to files only. With unified set to true, paths on Windows use /.
U.ls(PATH.public(), function(files, directories) {
console.log(files.length, directories.length);
}, /\.(jpg|png)$/);
var response = await U.ls(PATH.databases(), 'backup');
console.log(response.files);
method
U.ls2(path, [callback], [filter], [unified])
Lists files with their stats.
U.ls2(path, [callback], [filter], [unified])| Parameter | Type | Description |
|---|---|---|
path |
String |
The directory. |
callback? |
Function |
function(files, directories). |
filter? |
String|RegExp|Function |
A filter. |
unified? |
Boolean |
Uses / on Windows. Default: false |
Returns Promise|undefined A Promise without a callback.
Works like U.ls(), but each file is { filename, stats }, where stats is the fs.Stats object (size, dates). Directories are still paths.
U.ls2(PATH.temp(), function(files) {
var size = 0;
for (var file of files)
size += file.stats.size;
console.log(size.filesize());
});
method
U.encode(value)
Encodes HTML special characters.
U.encode(value)| Parameter | Type | Description |
|---|---|---|
value |
Object |
The value. |
Returns String
null and undefined give an empty string; other values are converted to a string first. It calls String.encode().
U.encode('<b>'); // '<b>'
method
U.decode(value)
Decodes HTML entities back to characters.
U.decode(value)| Parameter | Type | Description |
|---|---|---|
value |
Object |
The value. |
Returns String
The opposite of U.encode(). null and undefined give an empty string.
U.decode('<b>'); // '<b>'
method
U.btoa(value)
Encodes a string or a Buffer to Base64.
U.btoa(value)| Parameter | Type | Description |
|---|---|---|
value |
String|Buffer |
The value. |
Returns String
U.atob(value) decodes Base64 back to a UTF-8 string.
var encoded = U.btoa('hi'); // 'aGk='
var text = U.atob(encoded); // 'hi'
method
U.parseXML(xml, [replace])
Parses XML into a flat object.
U.parseXML(xml, [replace])| Parameter | Type | Description |
|---|---|---|
xml |
String |
The XML. |
replace? |
Boolean |
Replaces special characters in keys. Default: false |
Returns Object
Each key is the path of an element joined with dots, for example root.item; repeated elements give an array of values. Attributes are stored under the key with [], for example root.item[]. With replace set to true, the characters [, ], :, . and _ in keys become _. CDATA is read as text.
var obj = U.parseXML('<root><item id="1">A</item><item>B</item></root>');
// { 'root.item[]': { id: '1' }, 'root.item': ['A', 'B'] }
method
U.parseInt(value, [def])
Converts any value to an integer.
U.parseInt(value, [def])| Parameter | Type | Description |
|---|---|---|
value |
Object |
The value. |
def? |
Number |
Value for empty or invalid input. Default: 0 |
Returns Number
null, undefined and an empty string give def. A number is returned as it is. U.parseFloat(value, [def]) and U.parseBoolean(value, [def]) work the same way for decimals and booleans (def is false for booleans; a number is true when it is greater than 0).
var page = U.parseInt(this.query.page, 1);
var price = U.parseFloat(this.query.price);
var active = U.parseBoolean(this.query.active);
method
U.distance(lat1, lon1, lat2, lon2)
Returns the distance between two GPS coordinates in kilometres.
U.distance(lat1, lon1, lat2, lon2)| Parameter | Type | Description |
|---|---|---|
lat1 |
Number |
Latitude of the first point. |
lon1 |
Number |
Longitude of the first point. |
lat2 |
Number |
Latitude of the second point. |
lon2 |
Number |
Longitude of the second point. |
Returns Number Kilometres.
Uses the haversine formula on a sphere with a radius of 6371 km; the result has at most 3 decimal places.
U.distance(48.1486, 17.1077, 50.0755, 14.4378); // 289.225
method
U.minify_css(value)
Minifies CSS with the built-in compiler.
U.minify_css(value)| Parameter | Type | Description |
|---|---|---|
value |
String |
CSS code. |
Returns String
The same compiler the framework uses for static .css files.
U.minify_css('a { color: red; }'); // 'a{color:red}'
method
U.minify_js(value)
Minifies JavaScript with the built-in compiler.
U.minify_js(value)| Parameter | Type | Description |
|---|---|---|
value |
String |
JavaScript code. |
Returns String
Removes comments and white space. The same compiler the framework uses for static .js files.
U.minify_js('var a = 1; // note');
method
U.minify_html(value)
Minifies HTML with the built-in compiler.
U.minify_html(value)| Parameter | Type | Description |
|---|---|---|
value |
String |
HTML code. |
Returns String
Removes white space between tags.
U.minify_html('<div> <b>x</b> </div>'); // '<div><b>x</b></div>'
method
STATUS(id, data, [timeout])
since 0.0.63
Stores a named status of your app and passes it to DEF.onStatus(meta).
STATUS(id, data, [timeout])| Parameter | Type | Description |
|---|---|---|
id |
String|Object |
The name of the status, or a $ object. |
data |
Object |
Any value. |
timeout? |
Number |
Delays the update and merges calls in this time, in milliseconds. |
Returns undefined Nothing.
Each id has one status object { id, data, date }. STATUS() replaces its data, sets date and calls DEF.onStatus(meta) when you define it. Instead of an id you can pass a $ object; its ID (or name) is the id.
With timeout (in milliseconds), the update is delayed: the first call starts the timer, later calls only change data, and DEF.onStatus() runs once with the last data when the timer ends. Use it for values that change often, like a progress.
With CONF.allow_stats_status (default true), all statuses are added as status to the stats snapshot that Total.js writes to <main script>.json (CONF.allow_stats_snapshot).
DEF.onStatus = function(meta) {
console.log(meta.id, meta.data, meta.date);
};
for (var i = 0; i < items.length; i++)
STATUS('import', { done: i + 1, total: items.length }, 1000);
method
U.encrypt_data(value, key, [encode])
Encrypts a string with a key and a random mask.
U.encrypt_data(value, key, [encode])| Parameter | Type | Description |
|---|---|---|
value |
String |
The text to encrypt. |
key |
String |
The key. |
encode? |
String |
A Buffer encoding or buffer. Default: base64 |
Returns String|Buffer The encrypted value.
The output changes on every call because of a random 4-byte mask. encode is a Buffer encoding (default base64); buffer returns the raw Buffer. Read it back with U.decrypt_data() and the same key. This is light obfuscation, not a replacement for U.encrypt_crypto().
var token = U.encrypt_data(JSON.stringify({ id: user.id }), CONF.secret);
method
U.decrypt_data(value, key, [encode])
Decrypts a value made by U.encrypt_data().
U.decrypt_data(value, key, [encode])| Parameter | Type | Description |
|---|---|---|
value |
String|Buffer |
The encrypted value. |
key |
String |
The key used for encryption. |
encode? |
String |
The encoding of value. Default: base64 |
Returns String The decrypted text or null.
value is a string in the encode encoding (default base64) or a Buffer. Returns null when the value cannot be read. A wrong key gives a wrong string, not null, so check the result (for example with parseJSON()).
var data = (U.decrypt_data(token, CONF.secret) || '').parseJSON();
if (!data)
return $.invalid(401);
method
U.encrypt_crypto(type, key, value)
Encrypts data with a Node.js cipher.
U.encrypt_crypto(type, key, value)| Parameter | Type | Description |
|---|---|---|
type |
String |
A cipher name, for example aes-256-cbc. |
key |
String |
The key. |
value |
String|Buffer |
The data. |
Returns Buffer The encrypted data.
Uses Crypto.createCipheriv(type, key, CONF.default_crypto_iv). The key length must fit the cipher (32 characters for aes-256-cbc). CONF.default_crypto_iv is created from the app by default, so set it in the config when other apps must decrypt the data.
var key = 'a6e4c7d1b9f2038e5a7c1d4b6e8f0a2c';
var buffer = U.encrypt_crypto('aes-256-cbc', key, 'Hello');
var text = buffer.toString('base64');
method
U.decrypt_crypto(type, key, value)
Decrypts data made by U.encrypt_crypto().
U.decrypt_crypto(type, key, value)| Parameter | Type | Description |
|---|---|---|
type |
String |
The cipher name. |
key |
String |
The key. |
value |
Buffer |
The encrypted data. |
Returns Buffer The decrypted data or undefined.
Uses Crypto.createDecipheriv(type, key, CONF.default_crypto_iv). Returns undefined when the data cannot be decrypted.
var buffer = U.decrypt_crypto('aes-256-cbc', key, Buffer.from(text, 'base64'));
buffer && console.log(buffer.toString('utf8'));
method
U.convert62(number)
since 0.0.85
Converts a number to a base-62 string.
U.convert62(number)| Parameter | Type | Description |
|---|---|---|
number |
Number |
A positive number. |
Returns String
The alphabet is digits, then upper-case and lower-case letters. Decimals are floored. Read it back with U.from62().
U.convert62(123456789); // '8M0kX'
method
U.from62(value)
since 0.0.85
Converts a base-62 string from U.convert62() back to a number.
U.from62(value)| Parameter | Type | Description |
|---|---|---|
value |
String |
A base-62 string. |
Returns Number
U.from62(U.convert62(1000)); // 1000
method
U.groupify(id, [count])
since 0.0.88
Returns a fixed-length numeric group for an identifier.
U.groupify(id, [count])| Parameter | Type | Description |
|---|---|---|
id |
String |
An identifier. |
count? |
Number |
The number of digits. Default: 4 |
Returns String A string of digits.
The value is HASH(id, true) modulo 10^count, padded with zeros to count digits. The same id always gives the same group, so it is useful for spreading files into sub-directories.
var id = UID();
var filename = PATH.databases('files/' + U.groupify(id) + '/' + id + '.json');
method
U.parseBoolean(value, [def])
Converts any value to a boolean.
U.parseBoolean(value, [def])| Parameter | Type | Description |
|---|---|---|
value |
Object |
A value. |
def? |
Boolean |
The default value. Default: false |
Returns Boolean
A boolean is returned as it is, a number is true when greater than 0, other values are converted to a string and parsed with String.parseBoolean(). null and undefined return def.
var active = U.parseBoolean($.query.active);
method
U.parseFloat(value, [def])
Converts any value to a decimal number.
U.parseFloat(value, [def])| Parameter | Type | Description |
|---|---|---|
value |
Object |
A value. |
def? |
Number |
The default value. Default: 0 |
Returns Number
A number is returned as it is, other values are converted to a string and parsed with String.parseFloat(). null, undefined and an empty string return def.
var price = U.parseFloat(model.price, 0);
method
U.isDate(value)
Checks that a value is a valid Date.
U.isDate(value)| Parameter | Type | Description |
|---|---|---|
value |
Object |
A value. |
Returns Boolean
Returns false for an invalid date such as new Date('abc').
U.isDate(new Date()); // true
U.isDate(new Date('abc')); // false
U.isDate('2024-01-01'); // false
property
U.DAYS
English names of the days of the week.
U.DAYSReturns String Array
The array starts with Sunday, so it matches Date.getDay().
var name = U.DAYS[new Date().getDay()];
property
U.MONTHS
English names of the months.
U.MONTHSReturns String Array
The array starts with January, so it matches Date.getMonth().
var name = U.MONTHS[new Date().getMonth()];
method
U.httpstatus(code, [addCode])
Returns the text of an HTTP status code.
U.httpstatus(code, [addCode])| Parameter | Type | Description |
|---|---|---|
code |
Number |
An HTTP status code. |
addCode? |
Boolean |
Adds the code to the text. Default: true |
Returns String
The text comes from http.STATUS_CODES. With addCode (default true) the code is added in front.
U.httpstatus(404); // '404: Not Found'
U.httpstatus(404, false); // 'Not Found'
method
U.toURLEncode(obj)
Serializes an object into a URL-encoded query string.
U.toURLEncode(obj)| Parameter | Type | Description |
|---|---|---|
obj |
Object |
An object. |
Returns String For example q=total&page=2.
Strings are encoded with encodeURIComponent(), numbers and booleans are added as they are, arrays are joined with ,. null, undefined, empty strings and other objects (including dates) are skipped. Returns an empty string when nothing is added.
var url = 'https://example.com/api/?' + U.toURLEncode({ q: 'total js', page: 2, tags: ['a', 'b'] });
// q=total%20js&page=2&tags=a%2Cb
method
U.atob(value)
Decodes a base64 string to a UTF-8 string.
U.atob(value)| Parameter | Type | Description |
|---|---|---|
value |
String |
A base64 string. |
Returns String
The reverse of U.btoa().
U.atob(U.btoa('Hello')); // 'Hello'
method
U.isrelative(url)
Checks that a URL is relative.
U.isrelative(url)| Parameter | Type | Description |
|---|---|---|
url |
String |
A URL. |
Returns Boolean
Returns false when the URL starts with // or contains http:// or https://.
var url = $.query.redirect || '/';
if (!U.isrelative(url))
url = '/';
$.redirect(url);
method
U.isStaticFile(url)
Checks that a URL looks like a file.
U.isStaticFile(url)| Parameter | Type | Description |
|---|---|---|
url |
String |
A URL path. |
Returns Boolean
Returns true when the last 8 characters of the URL contain a dot, for example /img/logo.png.
U.isStaticFile('/img/logo.png'); // true
U.isStaticFile('/api/users/'); // false
method
U.resolve(url, [callback], [param])
Resolves the IPv4 address of a URL and caches it.
U.resolve(url, [callback], [param])| Parameter | Type | Description |
|---|---|---|
url |
String |
A URL. |
callback? |
Function |
function(err, uri, param, addresses). |
param? |
Object |
A value passed to the callback. |
Returns Array|undefined The cached addresses when no callback is given.
callback(err, uri, param, addresses) receives the parsed URL with uri.host replaced by the first address. The addresses are cached per host; without a callback the method returns the cached addresses (or undefined). A failed lookup is tried once more. The clear_dnscache command clears the cache.
U.resolve('https://www.totaljs.com', function(err, uri, param, addresses) {
console.log(err, addresses);
});
method
U.link(path1, [path2], [...])
since 0.0.39
Joins URL parts with exactly one / between them.
U.link(path1, [path2], [...])| Parameter | Type | Description |
|---|---|---|
path |
String |
One or more URL parts. |
Returns String
Unlike U.join(), it does not add a leading / and keeps the parts as they are.
U.link('https://example.com/', '/api/', 'users'); // 'https://example.com/api/users'
method
U.normalize(path)
since 0.0.39
Adds / to the start and the end of a path when it is missing.
U.normalize(path)| Parameter | Type | Description |
|---|---|---|
path |
String |
A path. |
Returns String
U.normalize('admin'); // '/admin/'
method
U.path(path, [delimiter])
Adds a trailing delimiter to a path when it is missing.
U.path(path, [delimiter])| Parameter | Type | Description |
|---|---|---|
path |
String |
A path. |
delimiter? |
String |
The delimiter. Default: / |
Returns String
An empty path returns the delimiter.
U.path('/www/app'); // '/www/app/'
method
U.getExtensionFromContentType(contentType)
since 0.0.63
Returns the file extension of a content type.
U.getExtensionFromContentType(contentType)| Parameter | Type | Description |
|---|---|---|
contentType |
String |
A content type. |
Returns String
Searches the content types known to U.getContentType() (including the ones added with U.setContentType()). Returns the first match without a dot, or undefined.
U.getExtensionFromContentType('image/png'); // 'png'
method
U.ObjectToArray(obj)
Converts an object into an array of { key, value } items.
U.ObjectToArray(obj)| Parameter | Type | Description |
|---|---|---|
obj |
Object |
An object. |
Returns Array
null or undefined returns EMPTYARRAY.
U.ObjectToArray({ a: 1, b: 2 }); // [{ key: 'a', value: 1 }, { key: 'b', value: 2 }]
method
U.createBuffer([value], [encoding])
Shortcut for Buffer.from(value || '', encoding).
U.createBuffer([value], [encoding])| Parameter | Type | Description |
|---|---|---|
value? |
String|Array|Buffer |
The data. Default: '' |
encoding? |
String |
The encoding of a string. Default: utf8 |
Returns Buffer
var buffer = U.createBuffer(body, 'base64');
method
U.createBufferSize([size])
Shortcut for Buffer.alloc(size || 0).
U.createBufferSize([size])| Parameter | Type | Description |
|---|---|---|
size? |
Number |
The size in bytes. Default: 0 |
Returns Buffer A buffer filled with zeros.
var buffer = U.createBufferSize(4);
buffer.writeInt32BE(100);
method
U.json2replacer(key, value)
A JSON.stringify() replacer that removes null and undefined values.
U.json2replacer(key, value)| Parameter | Type | Description |
|---|---|---|
key |
String |
The key. |
value |
Object |
The value. |
Returns Object
JSON.stringify({ id: 1, name: null }, U.json2replacer); // '{"id":1}'
property
U.queuecache
The state of the queues created by U.queue().
U.queuecacheReturns Object
An object keyed by the queue name. Each item has limit, running and pending (the waiting callbacks). Read it for monitoring only.
var item = U.queuecache.import;
item && console.log(item.running, item.pending.length);
class
new U.EventEmitter2([obj])
A small event emitter.
new U.EventEmitter2([obj])| Parameter | Type | Description |
|---|---|---|
obj? |
Object |
An object to extend. |
Returns EventEmitter2
new U.EventEmitter2() creates an emitter. U.EventEmitter2(obj) (without new) adds emit(), on(), once(), off(), removeListener() and removeAllListeners() to an existing object and returns it; U.EventEmitter2.extend(obj) does the same. Listeners are kept in $events. emit() passes up to 7 arguments and this is the emitter.
var service = {};
U.EventEmitter2(service);
service.on('ready', function(value) {
console.log('ready', value);
});
service.emit('ready', 1);
method
emitter.off(name, [fn])
since 0.0.90
Removes a listener or all listeners of an event.
emitter.off(name, [fn])| Parameter | Type | Description |
|---|---|---|
name |
String |
The event name. |
fn? |
Function |
The listener. |
Returns EventEmitter2 The emitter.
Without fn all listeners of name are removed. removeListener() is an alias. removeAllListeners([name]) removes the listeners of one event or of all events.
var fn = function() {};
emitter.on('change', fn);
emitter.off('change', fn);
method
U.Callback(count, [callback])
Calls a callback after next() was called count times.
U.Callback(count, [callback])| Parameter | Type | Description |
|---|---|---|
count |
Number |
How many next() calls to wait for. |
callback? |
Function |
The function to call. |
Returns Callback An instance with next() and done(fn).
Returns an instance with next() and done(callback). The callback runs once, when the pending count reaches zero. The class is also available as the global Callback.
var cb = U.Callback(3, function() {
console.log('all done');
});
for (var i = 0; i < 3; i++)
setTimeout(() => cb.next(), 100 * i);
method
U.chunker(name, [max])
Stores many items in temporary files, page by page.
U.chunker(name, [max])| Parameter | Type | Description |
|---|---|---|
name |
String |
A unique name, used in the file names. |
max? |
Number |
The number of items per file. Default: 50 |
Returns Chunker
Every max items written with write() go to one file {name}-{index}.chunker in the temp directory, compressed with deflate. Read them back page by page with each() or read(). Properties: compress (default true), autoremove (default true, removes each file after it is read), count, pages and percentage (progress of each()). The class is available as U.Chunker.
var chunker = U.chunker('export', 100);
for (var item of items)
chunker.write(item);
chunker.end();
chunker.each(function(items, next, index) {
console.log('page', index, items.length);
next();
}, function() {
console.log('done');
});
method
chunker.write(item)
Adds an item.
chunker.write(item)| Parameter | Type | Description |
|---|---|---|
item |
Object |
An item that can be serialized to JSON. |
Returns Chunker
When max items are waiting, they are written to a new file. append() is an alias. Call end() after the last item.
chunker.write({ id: 1, name: 'Peter' });
method
chunker.end()
Writes the remaining items to the last file.
chunker.end()Returns Chunker
chunker.end();
method
chunker.each(onItem, [onEnd])
Reads all pages one by one.
chunker.each(onItem, [onEnd])| Parameter | Type | Description |
|---|---|---|
onItem |
Function |
function(items, next, index). |
onEnd? |
Function |
Runs after the last page. |
Returns Chunker
onItem(items, next, index) gets the items of one page; call next() to read the next page. onEnd() runs after the last page. percentage shows the progress.
chunker.each(function(items, next) {
items.wait(save, next);
}, () => console.log('done'));
method
chunker.read(index, callback)
Reads one page.
chunker.read(index, callback)| Parameter | Type | Description |
|---|---|---|
index |
Number |
The page index from 0. |
callback |
Function |
function(err, items). |
Returns Chunker
callback(err, items) gets the items of the page, or an empty array when the file does not exist. It waits while files are still being written.
chunker.read(0, function(err, items) {
console.log(items);
});
method
chunker.clear()
Removes all files of the chunker.
chunker.clear()Returns Chunker
destroy() also removes the files and releases the instance.
chunker.clear();
method
U.reader([items])
Queries an array of objects with the NoSQL query builder.
U.reader([items])| Parameter | Type | Description |
|---|---|---|
items? |
Array|Object|String |
The items or a URL. |
Returns Reader
items is an array (or one object), or a URL of TextDB content that is downloaded and streamed. Without items, add data with reader.push(items) and finish with reader.push(null), or use reader.stream(stream). find(), list(), read(), count(), scalar(type, key, [key2]) and stats(groupfield, datefield, key, [type]) return a NoSQL query builder (where(), sort(), take(), callback()...). list() returns { page, pages, limit, count, items }. assign(data) creates a query from a serialized query object.
var reader = U.reader(users);
reader.find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {
console.log(response);
});
reader.count().callback(function(err, response) {
console.log(response);
});
method
reader.push(items)
Adds items to the reader.
reader.push(items)| Parameter | Type | Description |
|---|---|---|
items |
Array|Object|null |
The data, or null at the end. |
Returns undefined
Pass an array or one object for each chunk of data, then null to finish and get the results.
var reader = U.reader();
reader.find().where('active', true).callback(console.log);
reader.push(page1);
reader.push(page2);
reader.push(null);
method
U.streamer(beg, [end], callback, [skip], [stream])
Splits a stream of chunks into parts by delimiters.
U.streamer(beg, [end], callback, [skip], [stream])| Parameter | Type | Description |
|---|---|---|
beg |
String|Buffer |
The delimiter or the start of a part. |
end? |
String|Buffer |
The end of a part. |
callback |
Function |
function(value, index). |
skip? |
Number |
The number of parts to skip. Default: 0 |
stream? |
Stream |
A stream for the end event. |
Returns Function function(chunk).
Returns function(chunk) that you pass every chunk to. Without end, every part ends with beg (and includes it), for example a line ending with \n. With end, every part starts with beg and ends with end. callback(value, index) gets each part as a string; return false to stop. skip skips the first parts. With stream, the remaining data is processed on the stream end event. U.streamer2() is the same but gives Buffers.
var stream = F.Fs.createReadStream(PATH.databases('log.txt'));
stream.on('data', U.streamer('\n', function(line, index) {
console.log(index, line.trim());
}, stream));
method
U.streamer2(beg, [end], callback, [skip], [stream])
Same as U.streamer(), but the parts are Buffers.
U.streamer2(beg, [end], callback, [skip], [stream])| Parameter | Type | Description |
|---|---|---|
beg |
String|Buffer |
The delimiter or the start of a part. |
end? |
String|Buffer |
The end of a part. |
callback |
Function |
function(buffer, index). |
skip? |
Number |
The number of parts to skip. Default: 0 |
stream? |
Stream |
A stream for the end event. |
Returns Function function(chunk).
stream.on('data', U.streamer2('<item>', '</item>', function(buffer) {
console.log(buffer.length);
}));
method
U.filestreamer(filename)
since 0.0.59
Reads a text file line by line in batches.
U.filestreamer(filename)| Parameter | Type | Description |
|---|---|---|
filename |
String |
The file. |
Returns Object A stream reader.
Returns a TextDB stream reader. Set ondocuments (called with this.docs, the lines of one batch joined by ,; return false to stop) and $callback (called at the end), then call openread(). Set array = true to get docs as an array of lines. Lines that start with - are skipped.
var reader = U.filestreamer(PATH.databases('items.nosql'));
reader.ondocuments = function() {
var items = JSON.parse('[' + reader.docs + ']');
console.log(items.length);
};
reader.$callback = () => console.log('done');
reader.openread();
method
PATH.join(path1, [path2], [...])
since 0.0.39
Alias for Node.js path.join().
PATH.join(path1, [path2], [...])| Parameter | Type | Description |
|---|---|---|
path |
String |
One or more parts of the path. |
Returns String
var filename = PATH.join(PATH.root(), 'data', 'file.json');
method
PATH.exists(path, callback)
Checks that a file or directory exists.
PATH.exists(path, callback)| Parameter | Type | Description |
|---|---|---|
path |
String |
A path. |
callback |
Function |
function(exists, size, isFile). |
Returns undefined
callback(exists, size, isFile).
PATH.exists(PATH.public('robots.txt'), function(exists, size, isFile) {
console.log(exists, size, isFile);
});
method
PATH.verify(name)
Creates an app directory if it does not exist.
PATH.verify(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The directory name. |
Returns undefined
name is the name of a CONF.directory_{name} setting, for example databases. The check runs once per name.
PATH.verify('private');
method
PATH.ls(path, [callback], [filter], [unified])
Alias for U.ls().
PATH.ls(path, [callback], [filter], [unified])| Parameter | Type | Description |
|---|---|---|
path |
String |
The directory. |
callback? |
Function |
function(files, directories). |
Returns Promise|undefined
PATH.ls2() is an alias for U.ls2().
PATH.ls(PATH.private(), function(files) {
console.log(files);
});
method
PATH.unlink(files, [callback])
Removes files one by one.
PATH.unlink(files, [callback])| Parameter | Type | Description |
|---|---|---|
files |
String|String Array |
The files. |
callback? |
Function |
Runs at the end. |
Returns undefined
Errors are ignored.
PATH.unlink([PATH.temp('a.tmp'), PATH.temp('b.tmp')], () => console.log('removed'));
method
PATH.rmdir(directories, [callback])
Removes directories with all their content.
PATH.rmdir(directories, [callback])| Parameter | Type | Description |
|---|---|---|
directories |
String|String Array |
The directories. |
callback? |
Function |
Runs at the end. |
Returns undefined
Errors are ignored.
PATH.rmdir(PATH.temp('import'), () => console.log('removed'));
method
PATH.private([filename])
Returns a path in the private directory.
PATH.private([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_private (default /private/).
var filename = PATH.private('data.json');
method
PATH.models([filename])
Returns a path in the models directory.
PATH.models([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_models (default /models/).
var filename = PATH.models('file.js');
method
PATH.builds([filename])
Returns a path in the builds directory.
PATH.builds([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_builds (default /builds/).
var filename = PATH.builds('file.js');
method
PATH.views([filename])
Returns a path in the views directory.
PATH.views([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_views (default /views/).
var filename = PATH.views('index.html');
method
PATH.updates([filename])
Returns a path in the updates directory.
PATH.updates([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_updates (default /updates/).
var filename = PATH.updates('file.js');
method
PATH.modules([filename])
Returns a path in the modules directory.
PATH.modules([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_modules (default /modules/).
var filename = PATH.modules('file.js');
method
PATH.schemas([filename])
Returns a path in the schemas directory.
PATH.schemas([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_schemas (default /schemas/).
var filename = PATH.schemas('file.js');
method
PATH.extensions([filename])
Returns a path in the extensions directory.
PATH.extensions([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_extensions (default /extensions/).
var filename = PATH.extensions('file.js');
method
PATH.operations([filename])
Returns a path in the operations directory.
PATH.operations([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_operations (default /operations/).
var filename = PATH.operations('file.js');
method
PATH.tasks([filename])
Returns a path in the tasks directory.
PATH.tasks([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_tasks (default /tasks/).
var filename = PATH.tasks('file.js');
method
PATH.controllers([filename])
Returns a path in the controllers directory.
PATH.controllers([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_controllers (default /controllers/).
var filename = PATH.controllers('file.js');
method
PATH.definitions([filename])
Returns a path in the definitions directory.
PATH.definitions([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_definitions (default /definitions/).
var filename = PATH.definitions('file.js');
method
PATH.tests([filename])
Returns a path in the tests directory.
PATH.tests([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_tests (default /tests/).
var filename = PATH.tests('file.js');
method
PATH.services([filename])
Returns a path in the services directory.
PATH.services([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_services (default /services/).
var filename = PATH.services('file.js');
method
PATH.packages([filename])
Returns a path in the packages directory.
PATH.packages([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_packages (default /packages/).
var filename = PATH.packages('file.js');
method
PATH.themes([filename])
Returns a path in the themes directory.
PATH.themes([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_themes (default /themes/).
var filename = PATH.themes('default/index.html');
method
PATH.components([filename])
Returns a path in the components directory.
PATH.components([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_components (default /components/).
var filename = PATH.components('file.js');
method
PATH.templates([filename])
Returns a path in the templates directory.
PATH.templates([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_templates (default /templates/).
var filename = PATH.templates('email.html');
method
PATH.plugins([filename])
since 0.0.88
Returns a path in the plugins directory.
PATH.plugins([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_plugins (default /plugins/).
var filename = PATH.plugins('file.js');
method
PATH.flowstreams([filename])
Returns a path in the flowstreams directory.
PATH.flowstreams([filename])| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A file name. |
Returns String An absolute path.
The directory is CONF.directory_flowstreams (default /flowstreams/).
var filename = PATH.flowstreams('file.js');
method
OBSOLETE(name, message)
Prints a warning about obsolete code.
OBSOLETE(name, message)| Parameter | Type | Description |
|---|---|---|
name |
String |
What is obsolete. |
message |
String |
What to use instead. |
It writes the date, the name and the message to the console and increases F.stats.other.obsolete. Nothing is printed when CONF.nowarnings is true (the framework sets it when the watcher restarts the application with --restart).
function oldsave(model) {
OBSOLETE('oldsave()', 'Use save() instead.');
return save(model);
}
method
UID1([type], [date])
Generates a unique identifier with a decimal time part.
UID1([type], [date])| Parameter | Type | Description |
|---|---|---|
type? |
String |
A name of a separate counter. |
date? |
Date |
The time of the identifier. Default: NOW |
Returns String The identifier.
Like UID(), but the time part is the number of minutes since 2020-01-31 23:00 UTC written in decimal digits. Identifiers end with the version letter b. With type, every type has its own counter. date builds the identifier for another time.
var id = UID1();
var orderid = UID1('orders');