File storage
FILESTORAGE() and its methods, the file metadata, the @upload flag and file.fs().
On this page
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.
API
method
FILESTORAGE(name)
Returns a file storage by its name.
FILESTORAGE(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
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).
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'));
});
});
property
fs.name
The name of the storage.
fs.nameReturns String
The name given to FILESTORAGE(name).
property
fs.directory
The directory of the storage.
fs.directoryReturns String
The absolute path of the directory with the files, by default /databases/fs-{name}/. Set it with fs.storage(path).
method
fs.storage(path)
Changes the directory of the storage.
fs.storage(path)| Parameter | Type | Description |
|---|---|---|
path |
String |
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.
FILESTORAGE('videos').storage('/mnt/media/videos/');
method
fs.save(id, name, source, [custom], [callback], [expire], [headers])
Saves a file into the storage.
fs.save(id, name, source, [custom], [callback], [expire], [headers])| Parameter | Type | Description |
|---|---|---|
id |
String |
Your identifier of the file, for example from UID(). |
name |
String |
The file name with its extension. |
source |
String|Buffer|Stream |
A path, a Buffer, a readable stream or an https:// URL. |
custom? |
Object |
Custom data stored with the file. Default: null |
callback? |
Function |
Called as callback(err, meta). Without it the method returns a Promise. |
expire? |
String |
A time after which the file can no longer be read, such as '1 day'. |
headers? |
Object |
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.
FILESTORAGE('files').save(UID(), 'report.pdf', PATH.root('report.pdf'), function(err, meta) {
console.log(meta.id, meta.size);
});
var meta = await FILESTORAGE('exports').save(UID(), 'export.csv', Buffer.from(csv), { userid: $.user.id }, null, '1 day');
method
fs.insert(id, name, source, [custom], [callback], [expire], [headers])
An alias of fs.save().
fs.insert(id, name, source, [custom], [callback], [expire], [headers])Returns FileStorage|Promise
Works exactly as fs.save().
method
fs.savejson(id, value, [callback])
Saves a value as a JSON file.
fs.savejson(id, value, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the file. |
value |
Object |
A value to serialize. |
callback? |
Function |
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().
FILESTORAGE('data').savejson('settings', { theme: 'dark' }, function(err, meta) {});
method
fs.read(id, [callback], [nostream])
Reads a file as a stream.
fs.read(id, [callback], [nostream])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the file. |
callback? |
Function |
Called as callback(err, meta). Without it the method returns a Promise. |
nostream? |
Boolean |
true returns only the metadata. Default: false |
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.
FILESTORAGE('files').read('readme', function(err, meta) {
if (!err)
meta.stream.pipe(F.Fs.createWriteStream(PATH.tmp(meta.name)));
});
method
fs.readmeta(id, [callback], [keepfd])
Reads only the metadata of a file.
fs.readmeta(id, [callback], [keepfd])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the file. |
callback? |
Function |
Called as callback(err, meta, filename, fd). Without it the method returns a Promise. |
keepfd? |
Boolean |
true keeps the file descriptor open and passes it to the callback. Default: false |
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.
var meta = await FILESTORAGE('files').readmeta('readme');
console.log(meta.name, meta.size, meta.date);
method
fs.readbuffer(id, [callback])
Reads the whole content into a Buffer.
fs.readbuffer(id, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the file. |
callback? |
Function |
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.
var buffer = await FILESTORAGE('files').readbuffer('readme');
method
fs.readbase64(id, [callback])
Reads the content as a base64 string.
fs.readbase64(id, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the file. |
callback? |
Function |
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.
FILESTORAGE('photos').readbase64('avatar', function(err, base64, meta) {
var uri = 'data:' + meta.type + ';base64,' + base64;
});
method
fs.readjson(id, callback)
Reads a JSON file.
fs.readjson(id, callback)| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the file. |
callback |
Function |
Called as callback(err, value, meta). |
Returns FileStorage
Reads the content and parses it as JSON (dates included). The callback is required.
FILESTORAGE('data').readjson('settings', function(err, value) {
console.log(value.theme);
});
method
fs.readfilename(id)
Returns the path of the stored file.
fs.readfilename(id)| Parameter | Type | Description |
|---|---|---|
id |
String |
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.
method
fs.makedirectory(id)
Returns the directory for an id.
fs.makedirectory(id)| Parameter | Type | Description |
|---|---|---|
id |
String |
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.
method
fs.image(id, [callback])
Loads a stored file as an image.
fs.image(id, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the file. |
callback? |
Function |
Called as callback(err, image, meta). Without it the method returns a Promise. |
Returns FileStorage|Promise
Returns an image object of Images that reads the content of the file. Transform it and save or pipe it.
FILESTORAGE('photos').image('avatar', function(err, image) {
image.resize(100, 100);
image.save(PATH.public('thumbs/avatar.jpg'), function(err) {});
});
method
fs.http($, opt)
Sends a stored file as an HTTP response.
fs.http($, opt)| Parameter | Type | Description |
|---|---|---|
$ |
Controller |
The controller of the request. |
opt |
Object |
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.
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 });
});
};
ROUTE('GET /thumbs/{id}/', function($) {
FILESTORAGE('photos').http($, {
id: $.params.id,
cache: 'thumb-' + $.params.id,
image: image => image.resize(200, 200)
});
});
method
fs.remove(id, [callback])
Removes a file.
fs.remove(id, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the file. |
callback? |
Function |
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.
FILESTORAGE('files').remove($.params.id, function(err) {
$.success();
});
method
fs.rename(id, newname, [callback])
Changes the stored name of a file.
fs.rename(id, newname, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the file. |
newname |
String |
The new file name. |
callback? |
Function |
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.
await FILESTORAGE('files').rename('readme', 'README.md');
method
fs.copy(id, path, [callback])
Copies the content of a file out of the storage.
fs.copy(id, path, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the file. |
path |
String |
A target file name or a directory. |
callback? |
Function |
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.
FILESTORAGE('files').copy('readme', PATH.tmp(), function(err, meta) {
console.log(PATH.tmp(meta.name));
});
method
fs.clone(id, [newid], [callback])
Duplicates a file under a new id.
fs.clone(id, [newid], [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The id of the source file. |
newid? |
String |
The new id. Default: UID() |
callback? |
Function |
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.
FILESTORAGE('files').clone('template', function(err, meta) {
console.log(meta.id);
});
var meta = await FILESTORAGE('files').clone('template');
console.log(meta.id); // a new UID
method
fs.browse([callback])
Lists files from the index.
fs.browse([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
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. Each record is the metadata of a file.
FILESTORAGE('files').browse().where('ext', 'pdf').sort('date', true).take(10).callback(function(err, files) {
console.log(files);
});
method
fs.browse2([callback])
Lists files from the disk.
fs.browse2([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
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.
var files = await FILESTORAGE('files').browse2();
console.log(files.length);
method
fs.stream(onfile, [callback], [workers])
Walks all files of the storage.
fs.stream(onfile, [callback], [workers])| Parameter | Type | Description |
|---|---|---|
onfile |
Function |
Called as onfile(meta, next). |
callback? |
Function |
Called when all files were processed. |
workers? |
Number |
Parallel files. Default: 2 |
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.
var size = 0;
FILESTORAGE('files').stream(function(meta, next) {
size += meta.size;
next();
}, () => console.log(size));
method
fs.count2([callback])
Counts the files on the disk.
fs.count2([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
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.
var count = await FILESTORAGE('files').count2();
method
fs.rebuild([callback])
Rebuilds the index from the disk.
fs.rebuild([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
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.
await FILESTORAGE('files').rebuild();
method
fs.clear([callback])
Removes all files of the storage.
fs.clear([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
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.
FILESTORAGE('tmp').clear(function(err, count) {
console.log('Removed', count);
});
method
fs.drop([callback])
An alias of fs.clear().
fs.drop([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
Called as callback(err, count). Without it the method returns a Promise. |
Returns FileStorage|Promise
Works exactly as fs.clear().
method
fs.backup(filename, [callback])
Backs up the whole storage into one file.
fs.backup(filename, [callback])| Parameter | Type | Description |
|---|---|---|
filename |
String|Stream |
A target file name or a writable stream. |
callback? |
Function |
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 }.
var result = await FILESTORAGE('files').backup(PATH.root('files.backup'));
console.log(result.files, result.size);
method
fs.restore(filename, [callback])
Restores a backup.
fs.restore(filename, [callback])| Parameter | Type | Description |
|---|---|---|
filename |
String|Stream |
A backup file name or a readable stream. |
callback? |
Function |
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.
var fs = FILESTORAGE('files');
fs.restore(PATH.root('files.backup'), function(err) {
!err && fs.rebuild();
});
type
meta
The metadata of a stored file.
metaReturned 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 ornull,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.
type
ROUTE('POST /url/ @upload')
A route flag for multipart uploads.
ROUTE('POST /url/ @upload')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.
exports.install = function() {
ROUTE('POST /api/upload/ @upload <10MB', function($) {
var file = $.files[0];
file.fs('files', UID(), $.callback());
});
};
method
file.fs(storage, id, [callback])
Saves an uploaded file into a file storage.
file.fs(storage, id, [callback])| Parameter | Type | Description |
|---|---|---|
storage |
String |
The name of the storage. |
id |
String |
The id of the file. |
callback? |
Function |
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.
function upload($) {
$.files.wait(function(file, next) {
file.fs('files', UID(), next);
}, () => $.success());
}
method
Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])
Reads a file in chunks, with progress.
Utils.filestreamer(filename, onbuffer, [onend], [size], [offset])| Parameter | Type | Description |
|---|---|---|
filename |
String |
The path of the file. |
onbuffer |
Function |
Called as onbuffer(buffer, next, percentage); next(true) stops reading. |
onend? |
Function |
Called as onend(err) at the end, after a stop or on an error. |
size? |
Number |
The size of a chunk in bytes. Default: 16384 |
offset? |
Number |
The position in bytes where reading starts. Default: 0 |
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.
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'));
});