---
title: File storage
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/file-storage/
updated: 2026-11-19T16:17:02.153Z
---

# File storage

> FILESTORAGE() and its methods, the file metadata, the @upload flag and file.fs().

Methods of a file storage returned by `FILESTORAGE(name)` (written as `fs` below), the metadata of stored files, the route flag `@upload`, `file.fs()` for uploaded files and `Utils.filestreamer()`. For an introduction with examples read the guide [File storage](../../guides/file-storage/).

## API

### FILESTORAGE(name)

Type: `method`

Returns a file storage by its name.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The name of the storage. |

Returns: `FileStorage` The file storage.

Creates the storage on the first call and returns the same instance for the same name afterwards. The files are stored in `/databases/fs-{name}/`; the directory is created on the first save. Change it with `fs.storage(path)`.

Example: Save and read a file
```js
var fs = FILESTORAGE('files');

fs.save('readme', 'readme.txt', Buffer.from('Hello'), function(err, meta) {
	fs.readbuffer('readme', function(err, buffer) {
		console.log(buffer.toString('utf8'));
	});
});
```

### fs.name

Type: `property`

The name of the storage.

Returns: `String`

The name given to `FILESTORAGE(name)`.

### fs.directory

Type: `property`

The directory of the storage.

Returns: `String`

The absolute path of the directory with the files, by default `/databases/fs-{name}/`. Set it with `fs.storage(path)`.

### fs.storage(path)

Type: `method`

Changes the directory of the storage.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `path` | `String` | yes |  | An absolute path of the directory. |

Returns: `FileStorage` The storage itself.

Sets `fs.directory` and the path of the index `files.log` in it. Call it before you use the storage, for example in a definition file.

Example: Another disk
```js
FILESTORAGE('videos').storage('/mnt/media/videos/');
```

### fs.save(id, name, source, [custom], [callback], [expire], [headers])

Type: `method`

Saves a file into the storage.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | Your identifier of the file, for example from `UID()`. |
| `name` | `String` | yes |  | The file name with its extension. |
| `source` | `String|Buffer|Stream` | yes |  | A path, a `Buffer`, a readable stream or an `https://` URL. |
| `custom` | `Object` | no | `null` | Custom data stored with the file. |
| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |
| `expire` | `String` | no |  | A time after which the file can no longer be read, such as `'1 day'`. |
| `headers` | `Object` | no |  | HTTP headers for downloading a URL. |

Returns: `FileStorage|Promise` The storage, or a `Promise` with the metadata without a callback.

`source` is a path on the disk, a `Buffer`, a readable stream or an `https://` URL that is downloaded. The extension of `name` decides the content type; JPEG, PNG, GIF and SVG images get `width` and `height`. A path in `name` is removed, and a name longer than 250 characters is shortened. When you leave out `source`, `name` is used as the path of the file and its last part as the name. Saving again with an existing id replaces the file. `fs.insert()` is an alias.

The callback receives the metadata: `id`, `name`, `ext`, `type`, `size`, `width`, `height`, `custom`, `date` and `expire`.

Example: From a file on the disk
```js
FILESTORAGE('files').save(UID(), 'report.pdf', PATH.root('report.pdf'), function(err, meta) {
	console.log(meta.id, meta.size);
});
```

Example: With custom data and expiration
```js
var meta = await FILESTORAGE('exports').save(UID(), 'export.csv', Buffer.from(csv), { userid: $.user.id }, null, '1 day');
```

### fs.insert(id, name, source, [custom], [callback], [expire], [headers])

Type: `method`

An alias of fs.save().

Returns: `FileStorage|Promise`

Works exactly as `fs.save()`.

### fs.savejson(id, value, [callback])

Type: `method`

Saves a value as a JSON file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the file. |
| `value` | `Object` | yes |  | A value to serialize. |
| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |

Returns: `FileStorage|Promise`

Serializes `value` with `JSON.stringify()` and saves it as `{id}.json` (content type `application/json`). Read it back with `fs.readjson()`.

Example: Store settings
```js
FILESTORAGE('data').savejson('settings', { theme: 'dark' }, function(err, meta) {});
```

### fs.read(id, [callback], [nostream])

Type: `method`

Reads a file as a stream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the file. |
| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |
| `nostream` | `Boolean` | no | `false` | `true` returns only the metadata. |

Returns: `FileStorage|Promise`

The callback receives the metadata with a readable stream of the content in `meta.stream`. Consume the stream: it keeps the file open until it ends. With `nostream` set to `true` only the metadata is returned. An expired file ends with the error `File is expired`, a missing one with an error of the file system.

Example: Pipe into a file
```js
FILESTORAGE('files').read('readme', function(err, meta) {
	if (!err)
		meta.stream.pipe(F.Fs.createWriteStream(PATH.tmp(meta.name)));
});
```

### fs.readmeta(id, [callback], [keepfd])

Type: `method`

Reads only the metadata of a file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the file. |
| `callback` | `Function` | no |  | Called as `callback(err, meta, filename, fd)`. Without it the method returns a `Promise`. |
| `keepfd` | `Boolean` | no | `false` | `true` keeps the file descriptor open and passes it to the callback. |

Returns: `FileStorage|Promise`

Reads the header of the file and parses dates into `Date` objects. The callback also receives the path of the `.file` and, with `keepfd`, the open file descriptor, which you must close with `F.Fs.close()`. The expiration is not checked.

Example: Check a file
```js
var meta = await FILESTORAGE('files').readmeta('readme');
console.log(meta.name, meta.size, meta.date);
```

### fs.readbuffer(id, [callback])

Type: `method`

Reads the whole content into a Buffer.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the file. |
| `callback` | `Function` | no |  | Called as `callback(err, buffer, meta)`. Without it the method returns a `Promise`. |

Returns: `FileStorage|Promise`

Use it for small files; stream big files with `fs.read()`. The promise resolves with the buffer only.

Example: Read a file
```js
var buffer = await FILESTORAGE('files').readbuffer('readme');
```

### fs.readbase64(id, [callback])

Type: `method`

Reads the content as a base64 string.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the file. |
| `callback` | `Function` | no |  | Called as `callback(err, base64, meta)`. Without it the method returns a `Promise`. |

Returns: `FileStorage|Promise`

Handy for data URIs and JSON APIs. The promise resolves with the string only.

Example: A data URI
```js
FILESTORAGE('photos').readbase64('avatar', function(err, base64, meta) {
	var uri = 'data:' + meta.type + ';base64,' + base64;
});
```

### fs.readjson(id, callback)

Type: `method`

Reads a JSON file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the file. |
| `callback` | `Function` | yes |  | Called as `callback(err, value, meta)`. |

Returns: `FileStorage`

Reads the content and parses it as JSON (dates included). The callback is required.

Example: Read settings
```js
FILESTORAGE('data').readjson('settings', function(err, value) {
	console.log(value.theme);
});
```

### fs.readfilename(id)

Type: `method`

Returns the path of the stored file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the file. |

Returns: `String` The path.

Returns the absolute path of `{group}/{id}.file`. The file starts with a 2000-byte header, so do not serve it directly.

### fs.makedirectory(id)

Type: `method`

Returns the directory for an id.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the file. |

Returns: `String` The path.

Returns the path of the four-digit group directory where the file with this id is stored. It does not create the directory.

### fs.image(id, [callback])

Type: `method`

Loads a stored file as an image.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the file. |
| `callback` | `Function` | no |  | Called as `callback(err, image, meta)`. Without it the method returns a `Promise`. |

Returns: `FileStorage|Promise`

Returns an image object of [Images](../../guides/images/) that reads the content of the file. Transform it and save or pipe it.

Example: Create a thumbnail
```js
FILESTORAGE('photos').image('avatar', function(err, image) {
	image.resize(100, 100);
	image.save(PATH.public('thumbs/avatar.jpg'), function(err) {});
});
```

### fs.http($, opt)

Type: `method`

Sends a stored file as an HTTP response.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Controller` | yes |  | The controller of the request. |
| `opt` | `Object` | yes |  | The options: `id`, `download`, `check`, `image`, `cache`. |

Returns: `undefined`

Sets the content type, `Last-Modified`, `X-Size` (and `X-Width`, `X-Height` for images) and the HTTP cache (not in debug mode), answers `304` for a current version in the browser and supports `Range` requests with `206`. A missing or expired file, or a `check` that returns `false`, ends with `404`; such an id keeps answering `404` until the next clean-up of the framework cache.

Options: `id`; `download` (`true` for the stored name, a string, or a function `(name, type)` returning the name); `check` (a function `(meta)`); `image` (a function `(image)` with `this` as the controller, for image files); `cache` (a key under which a transformed image is kept in the temporary directory). The controller method `$.filefs()` is a shortcut.

Example: Serve and download
```js
exports.install = function() {
	ROUTE('GET /files/{id}/', function($) {
		FILESTORAGE('files').http($, { id: $.params.id });
	});
	ROUTE('GET /download/{id}/', function($) {
		FILESTORAGE('files').http($, { id: $.params.id, download: true });
	});
};
```

Example: A resized image
```js
ROUTE('GET /thumbs/{id}/', function($) {
	FILESTORAGE('photos').http($, {
		id: $.params.id,
		cache: 'thumb-' + $.params.id,
		image: image => image.resize(200, 200)
	});
});
```

### fs.remove(id, [callback])

Type: `method`

Removes a file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the file. |
| `callback` | `Function` | no |  | Called as `callback(err)`. Without it the method returns a `Promise`. |

Returns: `FileStorage|Promise`

Deletes the `.file` and its line in the index. The callback receives an error of the file system when the file does not exist.

Example: Remove a file
```js
FILESTORAGE('files').remove($.params.id, function(err) {
	$.success();
});
```

### fs.rename(id, newname, [callback])

Type: `method`

Changes the stored name of a file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the file. |
| `newname` | `String` | yes |  | The new file name. |
| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |

Returns: `FileStorage|Promise`

Writes the new name into the header of the file and into the index. The id and the content stay the same. A name longer than 250 characters is shortened.

Example: Rename
```js
await FILESTORAGE('files').rename('readme', 'README.md');
```

### fs.copy(id, path, [callback])

Type: `method`

Copies the content of a file out of the storage.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the file. |
| `path` | `String` | yes |  | A target file name or a directory. |
| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |

Returns: `Promise|undefined`

Writes the content without the header. When `path` contains a dot it is the target file name, otherwise it is a directory and the stored name is used.

Example: Export a file
```js
FILESTORAGE('files').copy('readme', PATH.tmp(), function(err, meta) {
	console.log(PATH.tmp(meta.name));
});
```

### fs.clone(id, [newid], [callback])

Type: `method`

Duplicates a file under a new id.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `id` | `String` | yes |  | The id of the source file. |
| `newid` | `String` | no | `UID()` | The new id. |
| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |

Returns: `Promise|undefined`

Copies the stored file with its metadata to a new id and adds it to the index. Without `newid` (also when the callback is the second argument, or in the Promise form) a new id from `UID()` is used; the callback and the Promise get the metadata with the new id.

Example: Clone
```js
FILESTORAGE('files').clone('template', function(err, meta) {
	console.log(meta.id);
});
```

Example: Promise
```js
var meta = await FILESTORAGE('files').clone('template');
console.log(meta.id); // a new UID
```

### fs.browse([callback])

Type: `method`

Lists files from the index.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | Called as `callback(err, files)`. |

Returns: `QueryBuilder` A NoSQL query builder.

Returns a NoSQL query builder over `files.log`, so you can use `where()`, `sort()`, `take()`, `fields()` and the other methods of [NoSQL](../../guides/nosql/). Each record is the metadata of a file.

Example: Latest PDF files
```js
FILESTORAGE('files').browse().where('ext', 'pdf').sort('date', true).take(10).callback(function(err, files) {
	console.log(files);
});
```

### fs.browse2([callback])

Type: `method`

Lists files from the disk.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | Called as `callback(err, files)`. Without it the method returns a `Promise`. |

Returns: `FileStorage|Promise`

Reads the header of every file in the directory and returns the array of metadata, each with `id` and `index`; expired files are skipped. It does not use the index, so it is slower than `browse()` but always matches the disk.

Example: All files
```js
var files = await FILESTORAGE('files').browse2();
console.log(files.length);
```

### fs.stream(onfile, [callback], [workers])

Type: `method`

Walks all files of the storage.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `onfile` | `Function` | yes |  | Called as `onfile(meta, next)`. |
| `callback` | `Function` | no |  | Called when all files were processed. |
| `workers` | `Number` | no | `2` | Parallel files. |

Returns: `FileStorage`

Calls `onfile(meta, next)` for every file on the disk with its metadata (without content), `id` and a sequence number `index`; expired files are skipped. Call `next()` to continue. `workers` is the number of files processed at the same time in a directory.

Example: Total size
```js
var size = 0;
FILESTORAGE('files').stream(function(meta, next) {
	size += meta.size;
	next();
}, () => console.log(size));
```

### fs.count2([callback])

Type: `method`

Counts the files on the disk.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | Called as `callback(err, count)`. Without it the method returns a `Promise`. |

Returns: `FileStorage|Promise`

Counts the files in the group directories of the storage.

Example: Count
```js
var count = await FILESTORAGE('files').count2();
```

### fs.rebuild([callback])

Type: `method`

Rebuilds the index from the disk.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | Called as `callback()`. Without it the method returns a `Promise`. |

Returns: `FileStorage|Promise`

Reads the metadata of all files and writes `files.log` again. Use it after `restore()` or after you copied `.file` files into the directory. `save()`, `read()`, `readbuffer()`, `copy()` and `clone()` wait while the index is written.

Example: Rebuild
```js
await FILESTORAGE('files').rebuild();
```

### fs.clear([callback])

Type: `method`

Removes all files of the storage.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | Called as `callback(err, count)`. Without it the method returns a `Promise`. |

Returns: `FileStorage|Promise`

Deletes every file, the group directories and the index. `save()`, `read()`, `readbuffer()`, `copy()` and `clone()` wait until it ends. Call it only when the directory of the storage exists: otherwise it ends with an error and the storage stays paused. The callback receives the number of removed files. `fs.drop()` is an alias.

Example: Clear
```js
FILESTORAGE('tmp').clear(function(err, count) {
	console.log('Removed', count);
});
```

### fs.drop([callback])

Type: `method`

An alias of fs.clear().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `callback` | `Function` | no |  | Called as `callback(err, count)`. Without it the method returns a `Promise`. |

Returns: `FileStorage|Promise`

Works exactly as `fs.clear()`.

### fs.backup(filename, [callback])

Type: `method`

Backs up the whole storage into one file.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String|Stream` | yes |  | A target file name or a writable stream. |
| `callback` | `Function` | no |  | Called as `callback(err, result)`. Without it the method returns a `Promise`. |

Returns: `Promise|undefined`

Writes every file, compressed with GZIP and encoded as base64, into a text file (or a writable stream). The index `files.log` is not included. The result is `{ filename, files, size }`.

Example: Backup
```js
var result = await FILESTORAGE('files').backup(PATH.root('files.backup'));
console.log(result.files, result.size);
```

### fs.restore(filename, [callback])

Type: `method`

Restores a backup.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String|Stream` | yes |  | A backup file name or a readable stream. |
| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |

Returns: `Promise|undefined`

Removes all current files and extracts a file made by `fs.backup()` into the directory. `save()`, `read()`, `readbuffer()`, `copy()` and `clone()` wait until it ends. Call `fs.rebuild()` afterwards to create the index.

Example: Restore and index
```js
var fs = FILESTORAGE('files');
fs.restore(PATH.root('files.backup'), function(err) {
	!err && fs.rebuild();
});
```

### meta

Type: `type`

The metadata of a stored file.

Returned by `save()`, `read()`, `readmeta()` and the other methods and stored in the header of each file:

- `id` {String}: the id,
- `name` {String}: the file name,
- `ext` {String}: the extension without the dot,
- `type` {String}: the content type,
- `size` {Number}: the size of the content in bytes,
- `width`, `height` {Number}: dimensions of JPEG, PNG, GIF and SVG images,
- `custom` {Object}: your custom data or `null`,
- `date` {Date}: when the file was saved,
- `expire` {Date}: when the file expires (only when set).

`read()` adds `stream`, and `stream()` and `browse2()` add `index`.

### ROUTE('POST /url/ @upload')

Type: `type`

A route flag for multipart uploads.

A route with `@upload` matches only `multipart/form-data` requests. The uploaded files are in `$.files` (also in actions), the other fields in `$.body`. Combine it with a size flag such as `<10MB`.

Example: An upload route
```js
exports.install = function() {
	ROUTE('POST /api/upload/ @upload <10MB', function($) {
		var file = $.files[0];
		file.fs('files', UID(), $.callback());
	});
};
```

### file.fs(storage, id, [callback])

Type: `method`

Saves an uploaded file into a file storage.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `storage` | `String` | yes |  | The name of the storage. |
| `id` | `String` | yes |  | The id of the file. |
| `callback` | `Function` | no |  | Called as `callback(err, meta)`. Without it the method returns a `Promise`. |

Returns: `FileStorage|Promise`

A method of `HttpFile` (the items of `$.files`). Saves the temporary file into `FILESTORAGE(storage)` with its original file name and returns the metadata.

Example: Save all uploads
```js
function upload($) {
	$.files.wait(function(file, next) {
		file.fs('files', UID(), next);
	}, () => $.success());
}
```

### Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])

Type: `method`

Reads a file in chunks, with progress.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `filename` | `String` | yes |  | The path of the file. |
| `onbuffer` | `Function` | yes |  | Called as `onbuffer(buffer, next, percentage)`; `next(true)` stops reading. |
| `onend` | `Function` | no |  | Called as `onend(err)` at the end, after a stop or on an error. |
| `size` | `Number` | no | `16384` | The size of a chunk in bytes. |
| `offset` | `Number` | no | `0` | The position in bytes where reading starts. |

Returns: `undefined`

Reads a file in chunks of `size` bytes (default 16384) from `offset` (default 0) and calls `onbuffer(buffer, next, percentage)` for each chunk. `percentage` is the part of the file read so far, from 0 to 100. Call `next()` to read the next chunk or `next(true)` to stop. `onend(err)` is called at the end of the file, after a stop, or with the error when the file does not exist. When the third argument is a number it is the size.

Example: Hash a file
```js
var hash = F.Crypto.createHash('sha1');
Utils.filestreamer(PATH.root('big.iso'), function(buffer, next) {
	hash.update(buffer);
	next();
}, function(err) {
	console.log(hash.digest('hex'));
});
```
