File storage
FILESTORAGE(), its methods, the meta object and the controller methods that serve stored files.
On this page
FILESTORAGE(name) returns a storage of binary files in databases/fs-{name}/. In this reference fs is a storage returned by FILESTORAGE() and meta the metadata of a file. The guide File storage explains how to save, read and serve files with examples.
API
method
FILESTORAGE(name)
Returns a file storage.
FILESTORAGE(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the storage. |
Returns FileStorage The storage.
Returns the storage name, stored in databases/fs-{name}/. The object is created on the first call and reused later. The folder is created when the first file is saved.
var fs = FILESTORAGE('photos');
fs.save(UID(), 'logo.png', PATH.public('img/logo.png'));
method
PATH.filestorage(name)
Returns the folder of a file storage.
PATH.filestorage(name)| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the storage. |
Returns String The absolute path of the folder.
Returns the path databases/fs-{name}/ inside the folder set by directory_databases.
console.log(PATH.filestorage('photos'));
// /www/app/databases/fs-photos/
property
fs.name
The name of the storage.
fs.nameReturns String
The name given to FILESTORAGE().
console.log(FILESTORAGE('photos').name); // photos
property
fs.directory
The folder of the storage.
fs.directoryReturns String
The absolute path of the folder with the files. Change it with fs.storage().
console.log(FILESTORAGE('photos').directory);
property
fs.total
The number of files.
fs.totalReturns Number
A counter kept in memory. It starts at 0; fs.count() and fs.rebuild() set it, and every saved file adds one.
var fs = FILESTORAGE('photos');
fs.count(function() {
console.log(fs.total, fs.size);
});
property
fs.size
The total size of the files in bytes.
fs.sizeReturns Number
A counter kept in memory. It starts at 0; fs.count() and fs.rebuild() set it, and every saved file adds its size.
var fs = FILESTORAGE('photos');
fs.count(function() {
console.log((fs.size / 1024 / 1024).floor(2) + ' MB');
});
method
fs.save(id, name, data, [callback], [custom], [expire], [headers])
Saves a file.
fs.save(id, name, data, [callback], [custom], [expire], [headers])| Parameter | Type | Description |
|---|---|---|
id |
String |
The ID of the file. |
name |
String |
The file name with its extension. |
data |
String|Buffer|Stream |
A path, a buffer, a readable stream or a URL. |
callback? |
Function |
function(err, meta), runs when the file is saved. |
custom? |
Object |
Any data kept with the file as meta.custom. |
expire? |
String |
A period such as '1 day'; after it the file cannot be read. |
headers? |
Object |
Headers for the request when data is a URL. |
Returns FileStorage|Promise The storage, or a promise with the meta object.
Stores data under id. The extension of name sets the content type; a path in name is reduced to the file name. data is a path to a file, a Buffer, a readable stream or an http:///https:// URL, which is downloaded first. For GIF, PNG, JPEG and SVG images the metadata also gets width and height. An existing file with the same ID is overwritten. Without a callback the method returns a promise. Alias: fs.insert().
FILESTORAGE('documents').save(UID(), 'note.txt', Buffer.from('Hello'), function(err, meta) {
console.log(meta.id, meta.size);
});
var meta = await FILESTORAGE('photos').save(UID(), 'photo.jpg', 'https://example.com/photo.jpg', null, { source: 'web' }, '30 days');
method
fs.insert(id, name, data, [callback], [custom], [expire], [headers])
Alias of fs.save().
fs.insert(id, name, data, [callback], [custom], [expire], [headers])| Parameter | Type | Description |
|---|---|---|
id |
String |
The ID of the file. |
name |
String |
The file name with its extension. |
data |
String|Buffer|Stream |
A path, a buffer, a readable stream or a URL. |
callback? |
Function |
function(err, meta). |
custom? |
Object |
Any data kept with the file. |
expire? |
String |
An expiration period. |
headers? |
Object |
Headers for a URL request. |
Returns FileStorage|Promise The storage, or a promise with the meta object.
The same method as fs.save().
FILESTORAGE('documents').insert(UID(), 'a.txt', Buffer.from('A'));
method
fs.savejson(id, value, [callback], [custom], [expire])
Saves an object as JSON.
fs.savejson(id, value, [callback], [custom], [expire])| Parameter | Type | Description |
|---|---|---|
id |
String |
The ID of the file. |
value |
Object |
The value to store. |
callback? |
Function |
function(err, meta). |
custom? |
Object |
Any data kept with the file. |
expire? |
String |
An expiration period. |
Returns FileStorage|Promise The storage, or a promise without a callback.
Serializes value with JSON.stringify() and saves it as {id}.json.
FILESTORAGE('data').savejson('settings', { theme: 'dark' });
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 |
function(err, meta). |
nostream? |
Boolean |
Do not open a stream of the content. Default: false |
Returns FileStorage|Promise The storage, or a promise with the meta object.
Gives the meta object with meta.stream, a readable stream of the content. With nostream set to true the meta object comes without the stream. Errors: File not found, Invalid file, File is expired or an error of the file system. Without a callback the method returns a promise.
FILESTORAGE('documents').read(id, function(err, meta) {
if (!err)
meta.stream.pipe(F.Fs.createWriteStream(PATH.temp(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 |
function(err, meta, filename, fd). |
keepfd? |
Boolean |
Keep the file descriptor fd open; you must close it. Default: false |
Returns FileStorage|Promise The storage, or a promise with the meta object.
Reads the header of the file. Dates come as Date objects. The callback also gets the path of the file on the disk. Unlike fs.read(), it does not check the expiration. Without a callback the method returns a promise.
FILESTORAGE('documents').readmeta(id, function(err, meta) {
console.log(meta.name, meta.type, meta.size);
});
method
fs.readbuffer(id, [callback])
Reads the content of a file into a Buffer.
fs.readbuffer(id, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The ID of the file. |
callback? |
Function |
function(err, buffer, meta). |
Returns FileStorage|Promise The storage, or a promise with the buffer.
Reads the whole file into memory. Use fs.read() for big files. Without a callback the method returns a promise. The promise gives only the buffer.
var buffer = await FILESTORAGE('documents').readbuffer(id);
method
fs.readbase64(id, [callback])
Reads the content of a file as Base64.
fs.readbase64(id, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The ID of the file. |
callback? |
Function |
function(err, base64, meta). |
Returns FileStorage|Promise The storage, or a promise with the string.
Reads the whole file and encodes it as a Base64 string. Without a callback the method returns a promise. The promise gives only the string.
FILESTORAGE('photos').readbase64(id, 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 |
function(err, value, meta). |
Returns FileStorage The storage.
Reads a file saved by fs.savejson() and parses it. The callback is required.
FILESTORAGE('data').readjson('settings', function(err, value) {
console.log(value.theme);
});
method
fs.image(id, [callback])
Reads a stored picture as an Image.
fs.image(id, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The ID of the file. |
callback? |
Function |
function(err, image, meta). |
Returns FileStorage|Promise The storage, or a promise with the image.
Gives an Image object that reads the content of the file, so you can resize or convert it and save the result. Image processing needs GraphicsMagick or ImageMagick. Without a callback the method returns a promise. The promise gives only the image.
FILESTORAGE('photos').image(id, function(err, image, meta) {
if (err)
return;
image.resize(200, 200);
image.save(PATH.temp('thumb_' + meta.name));
});
method
fs.res(res, options, [checkmeta])
Sends a file to an HTTP response.
fs.res(res, options, [checkmeta])| Parameter | Type | Description |
|---|---|---|
res |
Response |
The response object. |
options |
Object |
The options, see above. |
checkmeta? |
Function |
function(meta); return false to answer with 404. |
Returns undefined
The method behind controller.filefs() and controller.imagefs(). options: id (the file), download (true for the stored name, a string, or function(name, type) that returns the name), headers, done (a callback), nocompress, and for images image: true, make (function(image, res)) and cache (default true). It supports If-Modified-Since (304) and Range requests (206). A missing or expired file, or checkmeta(meta) that returns false, gives 404.
ROUTE('GET /files/{id}/', function(id) {
FILESTORAGE('documents').res(this.res, { id: id, download: true });
});
method
fs.copy(id, path, [callback])
since 0.0.97
Copies the content of a file to the disk.
fs.copy(id, path, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The ID of the file. |
path |
String |
A target file, or a folder. |
callback? |
Function |
function(err, meta). |
Returns FileStorage|Promise The storage, or a promise with the meta object.
Writes the content of the file (without the header) to path. A path with a dot is used as the file name; any other path is a folder and the file keeps its stored name. The folder must exist. Expired files give the error File is expired. Without a callback the method returns a promise.
FILESTORAGE('documents').copy(id, PATH.temp(), function(err, meta) {
console.log(PATH.temp(meta.name));
});
await FILESTORAGE('documents').copy(id, PATH.temp('invoice.pdf'));
method
fs.clone(id, [newid], [callback])
since 0.0.99
Copies a file inside the storage under a new ID.
fs.clone(id, [newid], [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The ID of the file. |
newid? |
String |
The ID of the copy. Default: UID() |
callback? |
Function |
function(err, meta); meta.id is the new ID. |
Returns FileStorage|Promise The storage, or a promise with the meta object.
Creates a copy of the file with the same metadata under newid and adds it to files.log. When the second argument is the callback, a new ID is generated with UID(). Expired files give the error File is expired. Without a callback the method returns a promise. In the promise form pass newid.
FILESTORAGE('documents').clone(id, function(err, meta) {
console.log('Copy:', meta.id);
});
var meta = await FILESTORAGE('documents').clone(id, UID());
method
fs.move(id, newid, [callback])
Changes the ID of a file.
fs.move(id, newid, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The ID of the file. |
newid |
String |
The new ID. |
callback? |
Function |
function(err). |
Returns FileStorage|Promise The storage, or a promise.
Moves the file to the name and folder of newid. files.log is not changed; call fs.rebuild() when you list files with fs.browse(). Without a callback the method returns a promise.
FILESTORAGE('documents').move('draft', 'final', function(err) {
console.log(err ? 'Error' : 'Moved');
});
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 (at most 250 characters). |
callback? |
Function |
function(err, meta). |
Returns FileStorage|Promise The storage, or a promise with the meta object.
Writes the new name into the header and into files.log. The content type stays the same. Without a callback the method returns a promise.
FILESTORAGE('documents').rename(id, 'contract-2024.pdf');
method
fs.remove(id, [callback])
Removes a file.
fs.remove(id, [callback])| Parameter | Type | Description |
|---|---|---|
id |
String |
The ID of the file. |
callback? |
Function |
function(err). |
Returns FileStorage|Promise The storage, or a promise.
Deletes the file from the disk and from files.log. Without a callback the method returns a promise.
FILESTORAGE('documents').remove(id, function(err) {
console.log(err ? 'Not found' : 'Removed');
});
method
fs.browse([callback])
Lists files from files.log.
fs.browse([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
function(err, files). |
Returns QueryBuilder The query builder.
Returns a NoSQL query builder over files.log, the database with the metadata of all files. Add conditions, sorting and paging, then callback().
FILESTORAGE('photos').browse().where('ext', 'jpg').sort('date_desc').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 |
function(err, files). |
Returns FileStorage|Promise The storage, or a promise with the array.
Reads the header of every file on the disk and returns their meta objects. Slower than fs.browse(), but it does not depend on files.log. Without a callback the method returns a promise.
var files = await FILESTORAGE('photos').browse2();
console.log(files.length);
method
fs.stream(onfile, [callback], [workers])
Goes through all files on the disk one by one.
fs.stream(onfile, [callback], [workers])| Parameter | Type | Description |
|---|---|---|
onfile |
Function |
function(meta, next). |
callback? |
Function |
Runs when all files are processed. |
workers? |
Number |
How many files are processed at the same time. |
Returns FileStorage The storage.
Calls onfile(meta, next) for every file; call next() to continue. meta.index is the order of the file. callback runs at the end.
FILESTORAGE('documents').stream(function(meta, next) {
if (meta.size > 1024 * 1024 * 10)
console.log(meta.id, meta.name);
next();
}, function() {
console.log('Done');
});
method
fs.count([callback])
Counts files and their size from files.log.
fs.count([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
function(err, response). |
Returns FileStorage The storage.
Gives an object with count (the number of files) and size (the total size in bytes), and updates fs.total and fs.size.
FILESTORAGE('photos').count(function(err, response) {
console.log(response.count, response.size);
});
method
fs.count2([callback])
Counts files on the disk.
fs.count2([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
function(err, count). |
Returns FileStorage|Promise The storage, or a promise with the number.
Counts the files in the subfolders of the storage, without files.log. Without a callback the method returns a promise.
var count = await FILESTORAGE('photos').count2();
method
fs.rebuild([callback])
Creates files.log again from the files on the disk.
fs.rebuild([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
Runs when the log is written. |
Returns FileStorage|Promise The storage, or a promise.
Reads all files with fs.browse2(), writes a new files.log and sets fs.total and fs.size. Use it after fs.move() or when files.log was lost. Without a callback the method returns a promise.
FILESTORAGE('photos').rebuild(function() {
console.log('files.log is ready');
});
method
fs.clean([callback])
Removes expired files.
fs.clean([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
function(err, count); count is the number of removed files. |
Returns FileStorage|Promise The storage, or a promise with the number.
Finds files whose expire date has passed in files.log and deletes them. Without a callback the method returns a promise.
ON('service', function(counter) {
if (counter % 1440 === 0)
FILESTORAGE('temporary').clean();
});
method
fs.clear([callback])
Removes all files.
fs.clear([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
function(err, count); count is the number of removed files. |
Returns FileStorage|Promise The storage, or a promise with the number.
Deletes all files, their subfolders and files.log. While it runs, other reads and saves wait. Without a callback the method returns a promise. Alias: fs.drop().
var count = await FILESTORAGE('temporary').clear();
method
fs.drop([callback])
Alias of fs.clear().
fs.drop([callback])| Parameter | Type | Description |
|---|---|---|
callback? |
Function |
function(err, count). |
Returns FileStorage|Promise The storage, or a promise with the number.
The same method as fs.clear().
FILESTORAGE('temporary').drop();
method
fs.backup(filename, [callback])
Writes all files into one backup file.
fs.backup(filename, [callback])| Parameter | Type | Description |
|---|---|---|
filename |
String|Stream |
The target file or a writable stream. |
callback? |
Function |
function(err, response); response has filename, files and size. |
Returns FileStorage|Promise The storage, or a promise with the response.
Each file is compressed with GZIP and written as Base64. filename is a path or a writable stream. Without a callback the method returns a promise.
FILESTORAGE('photos').backup(PATH.temp('photos.backup'), function(err, response) {
console.log(response.files, response.size);
});
method
fs.restore(filename, [callback])
Restores the storage from a backup file.
fs.restore(filename, [callback])| Parameter | Type | Description |
|---|---|---|
filename |
String |
The backup file. |
callback? |
Function |
function(err, meta). |
Returns FileStorage|Promise The storage, or a promise.
Removes all current files first (like fs.clear()), then unpacks the backup made by fs.backup(). Reads and saves wait until it ends. Without a callback the method returns a promise.
FILESTORAGE('photos').restore(PATH.temp('photos.backup'), function(err) {
FILESTORAGE('photos').rebuild();
});
method
fs.storage(directory)
Changes the folder of the storage.
fs.storage(directory)| Parameter | Type | Description |
|---|---|---|
directory |
String |
The absolute path of the folder. |
Returns FileStorage The storage.
Sets fs.directory and the path of files.log to another folder.
FILESTORAGE('archive').storage('/mnt/archive/files/');
method
fs.readfilename(id)
Returns the path of a file on the disk.
fs.readfilename(id)| Parameter | Type | Description |
|---|---|---|
id |
String |
The ID of the file. |
Returns String The absolute path.
Returns the path of the .file for id. The file starts with a header of 2000 bytes, so it is not a copy of the original file; use fs.copy() for that.
console.log(FILESTORAGE('photos').readfilename(id));
method
controller.filefs(name, id, [download], [headers], [callback], [checkmeta])
Answers with a file from a storage.
controller.filefs(name, id, [download], [headers], [callback], [checkmeta])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the storage. |
id |
String |
The ID of the file. |
download? |
Boolean|String|Function |
true, a file name, or function(name, type) that returns the name. |
headers? |
Object |
Extra response headers. |
callback? |
Function |
Runs when the file is sent. |
checkmeta? |
Function |
function(meta); return false to answer with 404. |
Returns Controller The controller.
Sends the file id of FILESTORAGE(name) with its stored content type. download set to true uses the stored name, a string sets another name. checkmeta(meta) that returns false gives 404. Range and If-Modified-Since requests are supported. The response object has the same method, res.filefs().
exports.install = function() {
ROUTE('GET /download/{id}/', download);
};
function download(id) {
this.filefs('documents', id, true);
}
method
controller.imagefs(name, id, make, [headers], [callback], [checkmeta])
Answers with a processed image from a storage.
controller.imagefs(name, id, make, [headers], [callback], [checkmeta])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name of the storage. |
id |
String |
The ID of the file. |
make |
Function |
function(image, res) that changes the image. |
headers? |
Object |
Extra response headers. |
callback? |
Function |
Runs when the image is sent. |
checkmeta? |
Function |
function(meta); return false to answer with 404. |
Returns Controller The controller.
Reads the picture id of FILESTORAGE(name), calls make(image, res) to process it and sends the result. The processed image is cached in the temporary folder per URL. Needs GraphicsMagick or ImageMagick. The response object has the same method, res.imagefs().
exports.install = function() {
ROUTE('GET /thumbnails/{id}/', thumbnail);
};
function thumbnail(id) {
this.imagefs('photos', id, function(image) {
image.resizeCenter(200, 200);
image.quality(80);
});
}
method
file.fs(storage, id, [custom], [expire], [callback])
Saves an uploaded file into a storage.
file.fs(storage, id, [custom], [expire], [callback])| Parameter | Type | Description |
|---|---|---|
storage |
String |
The name of the storage. |
id |
String |
The ID of the file. |
custom? |
Object |
Any data kept with the file. |
expire? |
String |
An expiration period. |
callback? |
Function |
function(err, meta). |
Returns FileStorage|Promise The storage, or a promise with the meta object.
A method of every file in controller.files. It calls FILESTORAGE(storage).save() with the original file name and the temporary file of the upload. Without a callback it returns a promise.
exports.install = function() {
ROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);
};
async function upload() {
var file = this.files[0];
var meta = await file.fs('documents', UID(), { user: this.user.id });
this.json({ id: meta.id, name: meta.name });
}