---
title: Static files
project: Total.js V4
version: 0.0.99
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v4/0-0-99/reference/static-files/
updated: 2026-11-18T16:57:34.578Z
---

# Static files

> File routes, the response methods for files, and the helpers and config of static files.

## API

### FILE(url, action, [flags])

Type: `method`

Creates a file route; `ROUTE('FILE /url/*.ext', action, [flags])` calls it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String|Function` | yes |  | The URL pattern, or a function `(req, res)` returning `true`. |
| `action` | `Function(req, res)|String` | yes |  | The handler, a file name or a URL. |
| `flags` | `Array` | yes |  | `#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/`.

Example: Protected downloads
```js
exports.install = function() {
	ROUTE('FILE /docs/*.pdf', function(req, res) {
		res.file(PATH.root('documents/' + U.getName(req.uri.pathname)));
	}, ['#auth']);
};
```

Example: A fixed file
```js
ROUTE('FILE /robots.txt', PATH.root('robots.txt'));
```

Example: Validation function
```js
FILE(function(req, res) {
	return req.uri.pathname.startsWith('/uploads/');
}, function(req, res) {
	res.continue();
}, ['#auth']);
```

### FILE404(fn)

Type: `method`

Sets a handler for static files that do not exist.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function(req, res)` | yes |  | 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.

Example: Placeholder image
```js
FILE404(function(req, res) {
	if (req.extension === 'jpg' || req.extension === 'png') {
		res.file(PATH.public('img/placeholder.png'));
		return true;
	}
});
```

### res.file(filename, [download], [headers], [callback])

Type: `method`

Sends a file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | An absolute path. |
| `download` | `String|Boolean` | yes |  | A download name, or `true` for the file name. |
| `headers` | `Object` | yes |  | Additional headers. |
| `callback` | `Function` | yes |  | 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.

Example: Download
```js
ROUTE('FILE /invoices/*.pdf', function(req, res) {
	var name = U.getName(req.uri.pathname);
	res.file(PATH.databases('invoices/' + name), 'invoice.pdf');
});
```

### res.image(filename, make, [headers], [callback], [persistent])

Type: `method`

Processes an image with GraphicsMagick or ImageMagick and sends the result.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String|Stream` | yes |  | The source image. |
| `make` | `Function(image, res)` | yes |  | Sets the image operations. |
| `headers` | `Object` | yes |  | Additional headers. |
| `callback` | `Function` | yes |  | Called when the image is sent. |
| `persistent` | `Boolean` | yes |  | 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.

Example: Thumbnails
```js
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);
	});
});
```

### res.filefs(name, id, [download], [headers], [callback], [checkmeta])

Type: `method`

Sends a file from a FileStorage.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The FileStorage name. |
| `id` | `String|Number` | yes |  | The file ID. |
| `download` | `String` | yes |  | A download name. |
| `headers` | `Object` | yes |  | Additional headers. |
| `callback` | `Function` | yes |  | Called when done. |
| `checkmeta` | `Function(meta)` | yes |  | 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.

Example: Files from storage
```js
ROUTE('FILE /files/*.*', function(req, res) {
	var id = U.getName(req.uri.pathname).replace(/\..*$/, '');
	res.filefs('files', id);
});
```

### res.imagefs(name, id, make, [headers], [callback], [checkmeta])

Type: `method`

Processes an image from a FileStorage and sends the result.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The FileStorage name. |
| `id` | `String|Number` | yes |  | The file ID. |
| `make` | `Function(image, res)` | yes |  | Sets the image operations. |
| `headers` | `Object` | yes |  | Additional headers. |
| `callback` | `Function` | yes |  | Called when done. |
| `checkmeta` | `Function(meta)` | yes |  | Checks the metadata of the file. |

Returns: `Response`

Like `res.filefs()`, but `make(image, res)` sets image operations as in `res.image()`.

Example: Avatars from storage
```js
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);
	});
});
```

### res.stream(type, stream, [download], [headers], [callback], [nocompress])

Type: `method`

Sends a readable stream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | The content type. |
| `stream` | `Stream` | yes |  | A readable stream. |
| `download` | `String` | yes |  | A download name. |
| `headers` | `Object` | yes |  | Additional headers. |
| `callback` | `Function` | yes |  | Called when done. |
| `nocompress` | `Boolean` | yes |  | 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`.

Example: Stream a file
```js
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']);
```

### res.continue([callback])

Type: `method`

Serves the requested static file from the public directory, as without a file route.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | yes |  | 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()`.

Example: Serve only to signed-in users
```js
ROUTE('FILE /private/*.*', function(req, res) {
	if (req.user)
		res.continue();
	else
		res.throw401();
});
```

### req.filecache(callback)

Type: `method`

Serves a generated file from `/tmp/`, or asks you to create it.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function(next, filename, req, res)` | yes |  | 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.

Example: Generated file
```js
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();
		});
	});
});
```

### req.extension

Type: `property`

The extension of a static-file request, without the dot.

Returns: `String`

Set for requests whose path ends with an extension (`req.isStaticFile` is `true`).

Example: Branch by extension
```js
FILE404(function(req, res) {
	if (req.extension === 'svg') {
		res.send(200, '<svg xmlns="http://www.w3.org/2000/svg"/>', 'image/svg+xml');
		return true;
	}
});
```

### LOCALIZE(url, [flags], [minify])

Type: `method`

Serves static files through the translator, or sets the language of requests.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String|Function` | yes |  | The URL pattern, or the language function. |
| `flags` | `String[]` | yes |  | `nocompress`, `.ext` and route flags such as `#middleware`. |
| `minify` | `Boolean` | yes |  | 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.

Example: Language and files
```js
LOCALIZE(function(req, res) {
	return (req.headers['accept-language'] || 'en').substring(0, 2);
});

LOCALIZE('/templates/*.html');
LOCALIZE('/texts/*.md', ['nocompress']);
```

### RESIZE(url, fn, [flags])

Type: `method`

Creates resized images on the fly for a URL.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | A URL path, optionally with `*.ext`. |
| `fn` | `Function(image)` | yes |  | Sets the image operations. |
| `flags` | `String[]` | yes |  | 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.

Example: Small images from /public/img/
```js
RESIZE('/img/small/*.jpg', function(image) {
	image.resize(200, 200);
	image.quality(80);
}, ['/img/']);
```

### MAP(url, filename, [filter])

Type: `method`

Serves a URL from another file or directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL. |
| `filename` | `String` | yes |  | A file or a directory. |
| `filter` | `String[]|Function` | yes |  | 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.

Example: File and directory
```js
MAP('/favicon.ico', '/img/favicon.ico');
MAP('/manuals/', '/files/manuals/', ['.pdf']);
```

### MERGE(url, file1, [file2], [fileN])

Type: `method`

Serves several files as one file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | The URL of the merged file. |
| `file1` | `String|String[]` | yes |  | 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.

Example: Bundle
```js
MERGE('/js/bundle.js', '/js/jquery.js', '/js/app.js');
MERGE('/css/bundle.css', ['/css/base.css', '/css/theme.css']);
```

### ACCEPT(extension, [type])

Type: `method`

Allows an extension for static files.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `extension` | `String` | yes |  | An extension, with or without the dot. |
| `type` | `String` | yes |  | The content type. |

Adds the extension to `static_accepts`. With `type`, it also sets the content type of the extension.

Example: 3D models
```js
ACCEPT('.glb', 'model/gltf-binary');
```

### TOUCH([url])

Type: `method`

Clears the cache of processed static files.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `url` | `String` | yes |  | 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.

Example: After a change
```js
require('fs').writeFile(PATH.public('css/theme.css'), css, function() {
	TOUCH('/css/theme.css');
});
```

### PATH.public([filename])

Type: `method`

Returns the absolute path to a file in the public directory.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | A relative file name. |

Returns: `String` An absolute path.

The directory is set by `directory_public`.

Example: Path
```js
var filename = PATH.public('img/logo.png');
```

### F.public(name, [theme])

Type: `method`

Returns the URL of a static file, with `static_url` and the `/versions` file applied.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | A file name. |
| `theme` | `String` | yes |  | 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.

Example: URLs
```js
F.public('/robots.txt');       // /robots.txt
F.public_font('icons.woff2');   // /fonts/icons.woff2
F.public_download('manual.pdf');  // /download/manual.pdf
```

### F.public_js(name, [theme])

Type: `method`

Returns the URL of a script, with `static_url_script` as the prefix.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | A file name. |
| `theme` | `String` | yes |  | A theme name. |

Returns: `String` A URL.

See `F.public()` for the rules.

Example: Script
```js
F.public_js('app.js'); // /js/app.js
```

### F.public_css(name, [theme])

Type: `method`

Returns the URL of a stylesheet, with `static_url_style` as the prefix.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | A file name. |
| `theme` | `String` | yes |  | A theme name. |

Returns: `String` A URL.

See `F.public()` for the rules.

Example: Stylesheet
```js
F.public_css('default.css'); // /css/default.css
```

### F.public_image(name, [theme])

Type: `method`

Returns the URL of an image, with `static_url_image` as the prefix.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | A file name. |
| `theme` | `String` | yes |  | A theme name. |

Returns: `String` A URL.

See `F.public()` for the rules.

Example: Image
```js
F.public_image('logo.png'); // /img/logo.png
```

### directory_public

Type: `config`

The directory with static files. Default `/public/`.

Returns: `String` '/public/'

Static-file requests are looked up here. `PATH.public()` builds paths into it.

Example: Config file
```text
directory_public : /www/
```

### static_url

Type: `config`

The prefix of URLs made by `F.public()`. Default empty.

Returns: `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.

Example: Config file
```text
static_url_image : https://cdn.example.com/img/
```

### static_url_script

Type: `config`

The prefix of URLs made by `F.public_js()`. Default `/js/`.

Returns: `String` '/js/'

See `static_url`.

Example: Config file
```text
static_url_script : /scripts/
```

### static_accepts

Type: `config`

The extensions that static files may have.

Returns: `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()`.

Example: Config file
```text
static_accepts_custom : glb, usdz
```

### allow_static_files

Type: `config`

Turns handling of static files on or off. Default `true`.

Returns: `Boolean` true

When `false`, paths with an extension are routed as normal requests and the public directory is not served.

Example: Config file
```text
allow_static_files : false
```

### allow_gzip

Type: `config`

Compresses static files with GZIP. Default `true`.

Returns: `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/`.

Example: Config file
```text
allow_gzip : false
```

### allow_compile

Type: `config`

Minifies static JavaScript, CSS and HTML. Default `true`.

Returns: `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.

Example: Config file
```text
allow_compile_script : false
```

### allow_localize

Type: `config`

Localizes static `.html` and `.htm` files. Default `true`.

Returns: `Boolean` true

The `@(Text)` markers in HTML files from `public/` are translated to the request language set with `LOCALIZE(fn)`.

Example: Config file
```text
allow_localize : false
```

### allow_persistent_images

Type: `config`

Stores images made by `res.image()` as persistent files. Default `true`.

Returns: `Boolean` true

The default for the `persistent` argument of `res.image()`.

Example: Config file
```text
allow_persistent_images : false
```

### etag_version

Type: `config`

A value added to the `ETag` of static files.

Returns: `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.

Example: Config file
```text
etag_version : 2
```

### default_root

Type: `config`

A URL prefix when the application runs under a sub-path.

Returns: `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.

Example: Config file
```text
default_root : /app/
```

### versions

Type: `config`

The `/versions` file in the root of the application maps file URLs to versioned URLs.

Returns: `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.

Example: Config file
```text
/js/app.js     : /js/app-2.js
/css/style.css : auto
/img/logo.png  --> /img/logo-2023.png
```

### MODIFY([filename], fn)

Type: `method`

Changes the content of views, styles and scripts before they are compiled.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | no |  | A path relative to the app, for example `'/views/index.html'`. |
| `fn` | `Function` | yes |  | `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.

Example: Add a banner to every view
```js
MODIFY(function(type, filename, value) {
	if (type === 'view')
		return value.replace('</body>', '<div class="banner">Beta</div></body>');
});
```

Example: One file only
```js
MODIFY('/views/index.html', function(type, filename, value) {
	return value.replace('@@VERSION@@', CONF.version);
});
```
