Static files
File routes, the response methods for files, and the helpers and config of static files.
On this page
API
method
FILE(url, action, [flags])
Creates a file route; ROUTE('FILE /url/*.ext', action, [flags]) calls it.
FILE(url, action, [flags])| Parameter | Type | Description |
|---|---|---|
url |
String|Function |
The URL pattern, or a function (req, res) returning true. |
action |
Function(req, res)|String |
The handler, a file name or a URL. |
flags |
Array |
#middleware, .ext, id:name, an options object. |
A file route handles requests for static files (paths that end with an extension) before the framework looks into public/. The first matching route wins; longer URLs are tested first.
The url forms:
| URL | Matches |
|---|---|
/photos/*.jpg | .jpg files under /photos/ |
/photos/* or /photos/*.* | any file under /photos/ |
/favicon.ico | exactly this file |
action is function(req, res). It can also be a string: an absolute file name to send with res.file(), or an http:///https:// URL whose response is streamed. Instead of a URL you can pass a function function(req, res) that returns true for the requests to handle.
Flags: #name adds middleware, .ext limits the extensions, id:name sets the route ID, and an object becomes $.options in middleware. For file routes, put middleware in the flags array, not inline in the URL. When the action does not answer itself, call res.continue() to serve the file from public/.
exports.install = function() {
ROUTE('FILE /docs/*.pdf', function(req, res) {
res.file(PATH.root('documents/' + U.getName(req.uri.pathname)));
}, ['#auth']);
};
ROUTE('FILE /robots.txt', PATH.root('robots.txt'));
FILE(function(req, res) {
return req.uri.pathname.startsWith('/uploads/');
}, function(req, res) {
res.continue();
}, ['#auth']);
method
FILE404(fn)
Sets a handler for static files that do not exist.
FILE404(fn)| Parameter | Type | Description |
|---|---|---|
fn |
Function(req, res) |
The handler. |
fn(req, res) is called instead of the 404 response for static files that are missing, not allowed by static_accepts, or not found by res.file(). Return true when you answered the request; otherwise the framework responds with 404.
FILE404(function(req, res) {
if (req.extension === 'jpg' || req.extension === 'png') {
res.file(PATH.public('img/placeholder.png'));
return true;
}
});
method
res.file(filename, [download], [headers], [callback])
Sends a file.
res.file(filename, [download], [headers], [callback])| Parameter | Type | Description |
|---|---|---|
filename |
String |
An absolute path. |
download |
String|Boolean |
A download name, or true for the file name. |
headers |
Object |
Additional headers. |
callback |
Function |
Called when the file is sent. |
Returns Response
filename is an absolute path; a leading @ means a file of a package. The content type comes from the extension of the request (or of the file). The file gets the same caching, GZIP compression, Range support and 304 Not Modified handling as files in public/. .html files are localized when allow_localize is on.
download adds Content-Disposition: attachment with this file name; true uses the name of the file. In release mode the framework remembers the file of each URL; call TOUCH(url) when it changes.
ROUTE('FILE /invoices/*.pdf', function(req, res) {
var name = U.getName(req.uri.pathname);
res.file(PATH.databases('invoices/' + name), 'invoice.pdf');
});
method
res.image(filename, make, [headers], [callback], [persistent])
Processes an image with GraphicsMagick or ImageMagick and sends the result.
res.image(filename, make, [headers], [callback], [persistent])| Parameter | Type | Description |
|---|---|---|
filename |
String|Stream |
The source image. |
make |
Function(image, res) |
Sets the image operations. |
headers |
Object |
Additional headers. |
callback |
Function |
Called when the image is sent. |
persistent |
Boolean |
Stores the result as a persistent file. |
Returns Response
filename is an absolute path or a readable stream. make(image, res) gets an image object and sets the operations (resize(), crop(), quality(), grayscale(), output()...). The result is stored in /tmp/ under the URL of the request and later requests get the stored file.
persistent stores the result as a persistent file (timg_ prefix in /tmp/) and reuses it while it exists; when omitted, it follows allow_persistent_images (default true). res.image_nocache(filename, make, [headers], [callback]) does the same without the cache.
ROUTE('FILE /thumbnails/*.jpg', function(req, res) {
res.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {
image.resize(150, 150);
image.quality(80);
});
});
method
res.filefs(name, id, [download], [headers], [callback], [checkmeta])
Sends a file from a FileStorage.
res.filefs(name, id, [download], [headers], [callback], [checkmeta])| Parameter | Type | Description |
|---|---|---|
name |
String |
The FileStorage name. |
id |
String|Number |
The file ID. |
download |
String |
A download name. |
headers |
Object |
Additional headers. |
callback |
Function |
Called when done. |
checkmeta |
Function(meta) |
Checks the metadata of the file. |
Returns Response
Reads the file id from FILESTORAGE(name) and sends it with its stored content type. checkmeta(meta) can inspect the metadata of the file before it is sent.
ROUTE('FILE /files/*.*', function(req, res) {
var id = U.getName(req.uri.pathname).replace(/\..*$/, '');
res.filefs('files', id);
});
method
res.imagefs(name, id, make, [headers], [callback], [checkmeta])
Processes an image from a FileStorage and sends the result.
res.imagefs(name, id, make, [headers], [callback], [checkmeta])| Parameter | Type | Description |
|---|---|---|
name |
String |
The FileStorage name. |
id |
String|Number |
The file ID. |
make |
Function(image, res) |
Sets the image operations. |
headers |
Object |
Additional headers. |
callback |
Function |
Called when done. |
checkmeta |
Function(meta) |
Checks the metadata of the file. |
Returns Response
Like res.filefs(), but make(image, res) sets image operations as in res.image().
ROUTE('FILE /avatars/*.jpg', function(req, res) {
var id = U.getName(req.uri.pathname).replace('.jpg', '');
res.imagefs('avatars', id, function(image) {
image.resize(100, 100);
});
});
method
res.stream(type, stream, [download], [headers], [callback], [nocompress])
Sends a readable stream.
res.stream(type, stream, [download], [headers], [callback], [nocompress])| Parameter | Type | Description |
|---|---|---|
type |
String |
The content type. |
stream |
Stream |
A readable stream. |
download |
String |
A download name. |
headers |
Object |
Additional headers. |
callback |
Function |
Called when done. |
nocompress |
Boolean |
Disables compression. |
Returns Response
The stream is compressed with GZIP when the content type can be compressed and the client accepts it, unless nocompress is true.
ROUTE('FILE /logs/*.txt', function(req, res) {
var stream = require('fs').createReadStream(PATH.logs(U.getName(req.uri.pathname)));
res.stream('text/plain', stream);
}, ['#admin']);
method
res.continue([callback])
Serves the requested static file from the public directory, as without a file route.
res.continue([callback])| Parameter | Type | Description |
|---|---|---|
callback |
Function |
Called when the file is sent. |
Returns Response
Use it in a file route or a middleware that decides not to answer the request itself. The extension must be in static_accepts; otherwise, and when the file does not exist, the response is 404 (or the FILE404() handler). It also applies MAP(), MERGE() and RESIZE().
ROUTE('FILE /private/*.*', function(req, res) {
if (req.user)
res.continue();
else
res.throw401();
});
method
req.filecache(callback)
Serves a generated file from /tmp/, or asks you to create it.
req.filecache(callback)| Parameter | Type | Description |
|---|---|---|
callback |
Function(next, filename, req, res) |
Creates the missing file. |
The file name in /tmp/ is built from the URL of the request. When the file exists, it is sent and callback is not called. Otherwise callback(next, filename, req, res) is called: write the file to filename, send the response (for example res.file(filename)), and call next(). At most 20 files are generated at the same time.
ROUTE('FILE /reports/*.csv', function(req, res) {
req.filecache(function(next, filename) {
require('fs').writeFile(filename, 'id;name\n1;Peter\n', function() {
res.file(filename);
next();
});
});
});
property
req.extension
The extension of a static-file request, without the dot.
req.extensionReturns String
Set for requests whose path ends with an extension (req.isStaticFile is true).
FILE404(function(req, res) {
if (req.extension === 'svg') {
res.send(200, '<svg xmlns="http://www.w3.org/2000/svg"/>', 'image/svg+xml');
return true;
}
});
method
LOCALIZE(url, [flags], [minify])
Serves static files through the translator, or sets the language of requests.
LOCALIZE(url, [flags], [minify])| Parameter | Type | Description |
|---|---|---|
url |
String|Function |
The URL pattern, or the language function. |
flags |
String[] |
nocompress, .ext and route flags such as #middleware. |
minify |
Boolean |
Minifies HTML. Default true. |
LOCALIZE(url) creates a file route that reads the files under url from public/, replaces @(Text) markers with translations in the request language, and caches the result per language in release mode. HTML is minified when allow_compile_html is on; the flag nocompress or minify = false turns it off.
The URL can end with a file pattern such as /templates/*.html. Without an extension, .html, .htm, .md and .txt files are handled; .ext flags choose others. A URL starting with # is a sitemap ID.
LOCALIZE(fn) sets the function fn(req, res, isStaticFile) that returns the language of a request. Static .html and .htm files from public/ are localized automatically when allow_localize is on.
LOCALIZE(function(req, res) {
return (req.headers['accept-language'] || 'en').substring(0, 2);
});
LOCALIZE('/templates/*.html');
LOCALIZE('/texts/*.md', ['nocompress']);
method
RESIZE(url, fn, [flags])
Creates resized images on the fly for a URL.
RESIZE(url, fn, [flags])| Parameter | Type | Description |
|---|---|---|
url |
String |
A URL path, optionally with *.ext. |
fn |
Function(image) |
Sets the image operations. |
flags |
String[] |
Source path or URL, .ext, nocache. |
Requests for images under url are made from the source images by fn(image) and cached in /tmp/. By default the source is the same path in public/. In flags, a path (/img/, or ~/absolute/path/) or an http(s):// URL sets where the source images are, .ext adds an extension, and nocache disables the cache. JPG, JPEG, PNG, GIF, APNG, HEIF and HEIC are always handled.
RESIZE('/img/small/*.jpg', function(image) {
image.resize(200, 200);
image.quality(80);
}, ['/img/']);
method
MAP(url, filename, [filter])
Serves a URL from another file or directory.
MAP(url, filename, [filter])| Parameter | Type | Description |
|---|---|---|
url |
String |
The URL. |
filename |
String |
A file or a directory. |
filter |
String[]|Function |
Filters the files of a directory. |
When filename has an extension, the URL is mapped to that file. Otherwise it is a directory and every file inside is mapped under url; filter is an array of extensions or a function (filename) that returns true for the files to map.
A relative filename is looked up in public/ first. Prefixes: ~ for a path from the application root, @ for a package, = for a theme. A url starting with # is a sitemap ID. The mapped file is still served only when its extension is allowed.
MAP('/favicon.ico', '/img/favicon.ico');
MAP('/manuals/', '/files/manuals/', ['.pdf']);
method
MERGE(url, file1, [file2], [fileN])
Serves several files as one file.
MERGE(url, file1, [file2], [fileN])| Parameter | Type | Description |
|---|---|---|
url |
String |
The URL of the merged file. |
file1 |
String|String[] |
Files to merge, in order. |
The files are joined into one file stored in /tmp/. Each argument can be a file name, a URL or an array. A file name with @ is from a package, with = from a theme. The url follows the /versions file.
MERGE('/js/bundle.js', '/js/jquery.js', '/js/app.js');
MERGE('/css/bundle.css', ['/css/base.css', '/css/theme.css']);
method
ACCEPT(extension, [type])
Allows an extension for static files.
ACCEPT(extension, [type])| Parameter | Type | Description |
|---|---|---|
extension |
String |
An extension, with or without the dot. |
type |
String |
The content type. |
Adds the extension to static_accepts. With type, it also sets the content type of the extension.
ACCEPT('.glb', 'model/gltf-binary');
method
TOUCH([url])
Clears the cache of processed static files.
TOUCH([url])| Parameter | Type | Description |
|---|---|---|
url |
String |
A URL such as /css/default.css. |
The framework remembers each processed file (minified, compressed or not found) by its URL. TOUCH(url) forgets one URL, so the next request reads the file again; TOUCH() forgets all.
require('fs').writeFile(PATH.public('css/theme.css'), css, function() {
TOUCH('/css/theme.css');
});
method
PATH.public([filename])
Returns the absolute path to a file in the public directory.
PATH.public([filename])| Parameter | Type | Description |
|---|---|---|
filename |
String |
A relative file name. |
Returns String An absolute path.
The directory is set by directory_public.
var filename = PATH.public('img/logo.png');
method
F.public(name, [theme])
Returns the URL of a static file, with static_url and the /versions file applied.
F.public(name, [theme])| Parameter | Type | Description |
|---|---|---|
name |
String |
A file name. |
theme |
String |
A theme name. |
Returns String A URL.
Relative names get the prefix of the helper: F.public() uses static_url, F.public_js() static_url_script, F.public_css() static_url_style, F.public_image() static_url_image, F.public_video() static_url_video, F.public_font() static_url_font and F.public_download() static_url_download. Names starting with / get no prefix. A name starting with ~ ignores the theme, =theme/ selects a theme (=?/ the default theme). With default_root, the root is added. Views use the same helpers.
F.public('/robots.txt'); // /robots.txt
F.public_font('icons.woff2'); // /fonts/icons.woff2
F.public_download('manual.pdf'); // /download/manual.pdf
method
F.public_js(name, [theme])
Returns the URL of a script, with static_url_script as the prefix.
F.public_js(name, [theme])| Parameter | Type | Description |
|---|---|---|
name |
String |
A file name. |
theme |
String |
A theme name. |
Returns String A URL.
See F.public() for the rules.
F.public_js('app.js'); // /js/app.js
method
F.public_css(name, [theme])
Returns the URL of a stylesheet, with static_url_style as the prefix.
F.public_css(name, [theme])| Parameter | Type | Description |
|---|---|---|
name |
String |
A file name. |
theme |
String |
A theme name. |
Returns String A URL.
See F.public() for the rules.
F.public_css('default.css'); // /css/default.css
method
F.public_image(name, [theme])
Returns the URL of an image, with static_url_image as the prefix.
F.public_image(name, [theme])| Parameter | Type | Description |
|---|---|---|
name |
String |
A file name. |
theme |
String |
A theme name. |
Returns String A URL.
See F.public() for the rules.
F.public_image('logo.png'); // /img/logo.png
config
directory_public
The directory with static files. Default /public/.
directory_publicReturns String '/public/'
Static-file requests are looked up here. PATH.public() builds paths into it.
directory_public : /www/
config
static_url
The prefix of URLs made by F.public(). Default empty.
static_urlReturns String ''
The other prefixes are static_url_script (/js/), static_url_style (/css/), static_url_image (/img/), static_url_video (/videos/), static_url_font (/fonts/) and static_url_download (/download/). They change only the generated URLs; files are still served from their path in public/. A prefix can be a full URL, for example of a CDN.
static_url_image : https://cdn.example.com/img/
config
static_url_script
The prefix of URLs made by F.public_js(). Default /js/.
static_url_scriptReturns String '/js/'
See static_url.
static_url_script : /scripts/
config
static_accepts
The extensions that static files may have.
static_acceptsReturns Object flac, jpg, jpeg, png, gif, ico, wasm, js, mjs, css, txt, xml, ...
Static files with other extensions answer 404. The default list: flac, jpg, jpeg, png, gif, ico, wasm, js, mjs, css, txt, xml, woff, woff2, otf, ttf, eot, svg, zip, rar, pdf, docx, xlsx, doc, xls, html, htm, appcache, manifest, map, ogv, ogg, mp4, mp3, webp, webm, swf, package, json, ui, md, m4v, jsx, heif, heic, ics, ts, m3u8, wav, xslt, xsd.
In the config file, static_accepts replaces the list, while static_accepts_custom adds extensions to it. Both take a comma-separated list. In code, use ACCEPT().
static_accepts_custom : glb, usdz
config
allow_static_files
Turns handling of static files on or off. Default true.
allow_static_filesReturns Boolean true
When false, paths with an extension are routed as normal requests and the public directory is not served.
allow_static_files : false
config
allow_gzip
Compresses static files with GZIP. Default true.
allow_gzipReturns Boolean true
Applies to text types: plain text, HTML, CSS, JavaScript, JSX, JSON, XML, SVG and Markdown, when the client sends Accept-Encoding: gzip. The compressed copy is stored in /tmp/.
allow_gzip : false
config
allow_compile
Minifies static JavaScript, CSS and HTML. Default true.
allow_compileReturns Boolean true
allow_compile_script (JavaScript and .mjs), allow_compile_style (CSS) and allow_compile_html (localized HTML) switch single types; all default to true. Files named like *.min.js, *-min.css or *.min@version.js are not minified. In CSS, url() values follow the /versions file.
allow_compile_script : false
config
allow_localize
Localizes static .html and .htm files. Default true.
allow_localizeReturns Boolean true
The @(Text) markers in HTML files from public/ are translated to the request language set with LOCALIZE(fn).
allow_localize : false
config
allow_persistent_images
Stores images made by res.image() as persistent files. Default true.
allow_persistent_imagesReturns Boolean true
The default for the persistent argument of res.image().
allow_persistent_images : false
config
etag_version
A value added to the ETag of static files.
etag_versionReturns String ''
When empty, it is set from version (without dots and spaces) at startup. Change version or etag_version to make browsers download changed files again.
etag_version : 2
config
default_root
A URL prefix when the application runs under a sub-path.
default_rootReturns String ''
With default_root : /app/, static URLs made by F.public() and the views start with /app/, and the /versions file is applied with this prefix.
default_root : /app/
config
versions
The /versions file in the root of the application maps file URLs to versioned URLs.
versionsReturns File
Each line is url : newurl. The value auto adds a hash of the file content to the name at startup (/js/app.js becomes /js/app-<hash>.js). With --> instead of :, the new URL is also mapped to the original file. Lines starting with # or // are comments. The helpers F.public_*(), MERGE() and views use the new URLs.
/js/app.js : /js/app-2.js
/css/style.css : auto
/img/logo.png --> /img/logo-2023.png
method
MODIFY([filename], fn)
Changes the content of views, styles and scripts before they are compiled.
MODIFY([filename], fn)| Parameter | Type | Description |
|---|---|---|
filename? |
String |
A path relative to the app, for example '/views/index.html'. |
fn |
Function |
function(type, filename, value, controller) that returns the new content. |
The function is called with (type, filename, value, controller), where type is 'view', 'style', 'script' or 'static' (a static file localized by Total.js) and filename is the path relative to the app with a leading /. Return the new content; a falsy result keeps it as it was.
With filename (for example '/views/index.html') the function runs only for that file. The change is made in memory, the file on the disk stays as it is. In release mode compiled content is cached, so the function runs once per file. A function registered by a plugin or a module is removed when it is uninstalled.
MODIFY(function(type, filename, value) {
if (type === 'view')
return value.replace('</body>', '<div class="banner">Beta</div></body>');
});
MODIFY('/views/index.html', function(type, filename, value) {
return value.replace('@@VERSION@@', CONF.version);
});