File storage
Store, read, serve and manage binary files with FILESTORAGE(), including uploaded files.
On this page
A file storage keeps binary files (uploads, documents, images, exports) on the disk under your own identifiers. You never deal with paths: you save a file with an id and read it back with the same id. Each storage is a directory with sub-directories and an index file, and the name, the content type, the size and custom data of every file travel with the file itself.
var fs = FILESTORAGE('photos');
fs.save('avatar-100', 'me.jpg', PATH.root('me.jpg'), function(err, meta) {
// meta.name === 'me.jpg', meta.type === 'image/jpeg', meta.width, meta.height
});FILESTORAGE(name) returns the same instance for the same name during the life of the process, so call it wherever you need it. The full list of methods is in the reference of File storage.
Where files are stored
A storage named photos lives in /databases/fs-photos/. Every file is written to {group}/{id}.file, where {group} is a four-digit directory computed from a hash of the id (/databases/fs-photos/0417/avatar-100.file), so large storages do not end up with thousands of files in one directory. The directory is created on the first save.
Each .file starts with a 2000-byte header that holds the metadata as JSON, followed by the content. The storage also appends one line per saved file to files.log, a NoSQL index used by browse(). Change the directory of a storage with fs.storage(path):
FILESTORAGE('backups').storage('/mnt/disk2/backups/');Saving files
fs.save(id, name, source, [custom], [callback], [expire], [headers]) (alias insert()) accepts four kinds of source:
- the path of a file on the disk,
- a
Buffer, - a readable stream,
- an
https://URL, which is downloaded (optionalheadersare sent with the request; a response with status 400 or higher ends with an error).
The id is up to you; UID() gives a unique one. name is the original file name: its extension decides the content type, and for JPEG, PNG, GIF and SVG files the width and height are measured during the save. custom is any value you want to keep with the file (the owner, a description...). expire is a time such as '1 day' or '30 minutes': after that time the file can no longer be read. Without a callback the method returns a Promise.
var fs = FILESTORAGE('documents');
// From a Buffer, with custom data
fs.save(UID(), 'note.txt', Buffer.from('Hello', 'utf8'), { userid: 'u1' }, function(err, meta) {
console.log(meta.id, meta.size, meta.custom.userid);
});
// From a URL, as a Promise, expires in 7 days
var meta = await fs.save('logo', 'logo.png', 'https://www.example.com/logo.png', null, null, '7 days');The callback receives the metadata of the saved file:
| Property | Content |
|---|---|
id | The id of the file |
name | The file name (without a path, at most 250 characters) |
ext | The extension, lower case without the dot |
type | The content type, for example image/png |
size | The size of the content in bytes |
width, height | The dimensions of JPEG, PNG, GIF and SVG images |
custom | Your custom data, or null |
date | When the file was saved |
expire | When the file expires, if you set it |
Saving again with an existing id replaces the file. fs.savejson(id, value, [callback]) is a shortcut that stores a value as {id}.json.
Uploaded files
Files of a multipart/form-data request are in $.files, in a route and in an action alike. Each item is an HttpFile, and file.fs(storage, id, [callback]) saves it into a storage with its original file name. The flag @upload makes the route accept only multipart requests; a size flag such as <10MB raises the size limit of the body.
exports.install = function() {
ROUTE('POST /api/upload/ @upload <10MB', upload);
};
function upload($) {
var file = $.files[0];
if (!file) {
$.invalid('@(Select a file)');
return;
}
file.fs('files', UID(), function(err, meta) {
if (err)
$.invalid(err);
else
$.success(meta.id);
});
}Several files are saved one after another with wait():
function upload($) {
var output = [];
$.files.wait(function(file, next) {
file.fs('files', UID(), function(err, meta) {
meta && output.push({ id: meta.id, name: meta.name, size: meta.size });
next();
});
}, () => $.json(output));
}The properties of HttpFile and its other methods are described in Controller.
Reading files
| Method | The callback receives |
|---|---|
fs.read(id, callback) | (err, meta) with a readable stream in meta.stream |
fs.readmeta(id, callback) | (err, meta): only the header, the content is not read |
fs.readbuffer(id, callback) | (err, buffer, meta): the whole content |
fs.readbase64(id, callback) | (err, base64, meta): the content as a base64 string |
fs.readjson(id, callback) | (err, value, meta): the parsed JSON |
fs.image(id, callback) | (err, image, meta): an image object of Images |
A missing file ends with an error from the file system, an expired one with the error File is expired. Except readjson(), the methods return a Promise without a callback; the promise resolves with the second argument of the callback.
var fs = FILESTORAGE('documents');
fs.read('invoice-2025-001', function(err, meta) {
if (err)
return;
var writer = F.Fs.createWriteStream(PATH.tmp(meta.name));
meta.stream.pipe(writer);
});
var buffer = await fs.readbuffer('invoice-2025-001');Always consume meta.stream from read(): it holds an open file descriptor until it ends. Pass true as the third argument of read() when you only need the metadata.
Serving files over HTTP
fs.http($, opt) sends a stored file as the response of a route. It sets the content type, Last-Modified and the HTTP cache headers, answers 304 when the browser has the current version, supports Range requests (audio and video seeking) and answers 404 when the file does not exist or has expired. $.filefs(name, id, [download], [check]) of the controller is a shortcut for it.
exports.install = function() {
ROUTE('GET /files/{id}/', file);
ROUTE('GET /download/{id}/', download);
};
function file($) {
FILESTORAGE('files').http($, { id: $.params.id });
}
function download($) {
FILESTORAGE('files').http($, {
id: $.params.id,
download: true,
check: meta => meta.custom && meta.custom.public
});
}The options are:
id: the id of the file,download:truesends the file as an attachment with its stored name, a string sets another name, a function(name, type)returns the name,check: a function(meta); when it returnsfalsethe answer is404,image: a function(image)called withthisas the controller, to transform JPEG, PNG and other images before they are sent,cache: a key; withimage, the transformed image is saved to the temporary directory under this key and reused for the next requests.
function thumbnail($) {
var id = $.params.id;
FILESTORAGE('photos').http($, {
id: id,
cache: 'thumb-' + id,
image: function(image) {
image.resize(200, 200);
image.quality(80);
}
});
}An id that ended with 404 once is remembered and answered with 404 until the next periodic clean-up of the framework, so keep ids of removed files unique.
Managing files
var fs = FILESTORAGE('documents');
fs.rename('note-1', 'renamed.txt'); // changes the stored name
fs.copy('note-1', PATH.tmp()); // writes the content to a directory or a file path
fs.clone('note-1', 'note-2'); // a new id with the same content
fs.remove('note-2', function(err) {}); // deletes the file and its line in the indexclone(id, [newid], [callback]) creates an id with UID() when newid is missing, and the callback or the Promise gets the metadata with that id. copy(id, path) writes to path as a file name when it contains a dot, otherwise into the directory path with the stored name.
fs.clear() (alias drop()) removes all files of the storage and the index; the callback receives the number of removed files.
Listing files
fs.browse() reads the index files.log and returns a NoSQL query builder, so you can filter, sort and page the files as in NoSQL:
FILESTORAGE('documents').browse().where('ext', 'pdf').sort('date', true).take(20).callback(function(err, files) {
console.log(files);
});fs.browse2() reads the headers of all files on the disk instead of the index, and fs.stream(onfile, [callback], [workers]) walks the files one by one. fs.count2() counts the files on the disk. fs.rebuild() writes the index again from the files on the disk, which you need after you copied files into the directory yourself or after restore().
FILESTORAGE('documents').stream(function(meta, next) {
console.log(meta.id, meta.name, meta.size);
next();
}, function() {
console.log('done');
});Backup and restore
fs.backup(filename, [callback]) writes all files of the storage, each compressed with GZIP, into one text file and returns { filename, files, size }. fs.restore(filename, [callback]) removes the current files and restores the backup. The index is not part of the backup, so call rebuild() after a restore.
var fs = FILESTORAGE('documents');
await fs.backup(PATH.root('documents.backup'));
fs.restore(PATH.root('documents.backup'), function(err) {
fs.rebuild();
});While a storage is cleared, restored or its index is rebuilt, its save(), read(), readbuffer(), copy() and clone() calls wait until the operation ends.