File storage
Save, read, serve and manage binary files with FILESTORAGE().
On this page
FILESTORAGE(name) returns a file storage: a folder on the disk that keeps binary files under an ID, together with their name, content type, size and other metadata. Use it for uploads, attachments, photos and exports that the application stores itself. The full list of methods is in the reference of File storage.
var fs = FILESTORAGE('photos');
fs.save(UID(), 'logo.png', PATH.public('img/logo.png'), function(err, meta) {
// meta.id, meta.name, meta.size, meta.type, meta.width, meta.height
console.log(meta);
});The first call creates the storage object; later calls with the same name return the same object.
Where the files live
A storage named photos lives in databases/fs-photos/ (PATH.filestorage('photos'), inside the folder set by directory_databases). Files are spread into subfolders with four-digit names, computed from a hash of the ID, so one folder never holds too many files:
databases/
fs-photos/
files.log
0384/
1fs3001xb41f.file
7712/
1fs3002xb41f.file- Each
.filehas a header of 2000 bytes with the metadata as JSON, followed by the content of the file. files.logis a NoSQL text database with the metadata of all files.browse()andcount()read it;save(),rename(),remove()andclean()keep it up to date;rebuild()creates it again from the files.
The ID is part of the file name on the disk. Use IDs that you generate (UID()), and never pass an unchecked value from a request as the ID.
Saving files
save(id, name, data, [callback], [custom], [expire], [headers]) stores data under id. name is the file name with its extension; the extension sets the content type. data can be:
- a path to a file on the disk,
- a
Buffer, - a readable stream,
- a URL (
http://orhttps://): the file is downloaded first;headersare sent with that request.
var fs = FILESTORAGE('documents');
// From a buffer, with custom data and an expiration
fs.save(UID(), 'report.txt', Buffer.from('Hello'), function(err, meta) {
console.log(meta.id, meta.expire);
}, { user: 'admin' }, '7 days');
// From a URL, as a promise
var meta = await fs.save(UID(), 'avatar.jpg', 'https://example.com/avatar.jpg');custom is any value you want to keep with the file; it comes back as meta.custom. expire is a period such as '1 hour' or '7 days': after it, the file can no longer be read and clean() removes it. savejson(id, value) saves an object as a JSON file and readjson(id, callback) reads it back.
The meta object
Every read returns the metadata of the file:
| Property | What it contains |
|---|---|
id | The ID of the file |
name | The file name (at most 250 characters) |
ext | The extension, without the dot |
type | The content type, from the extension |
size | The size of the content in bytes |
date | When the file was saved |
width, height | The dimensions of a GIF, PNG, JPEG or SVG image |
custom | The custom value given to save() |
expire | The expiration date, when expire was given to save() |
Reading files
var fs = FILESTORAGE('documents');
// A stream of the content
fs.read(id, function(err, meta) {
if (err)
return;
meta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));
});
// Only the metadata
fs.readmeta(id, function(err, meta) {
console.log(meta.name, meta.size);
});
// The whole content in memory
fs.readbuffer(id, function(err, buffer, meta) {
console.log(buffer.length);
});read() gives an error File not found, Invalid file or File is expired, or the error of the file system when the file does not exist. Pass true as the third argument of read() to get the metadata without opening a stream. readbase64() returns the content as a Base64 string, and image(id, callback) returns an Image object to resize or convert the stored picture.
Without a callback, most methods return a promise:
var meta = await FILESTORAGE('documents').read(id, null, true);
var buffer = await FILESTORAGE('documents').readbuffer(id);Serving files over HTTP
A controller sends a stored file with this.filefs(name, id, [download], [headers], [callback], [checkmeta]):
exports.install = function() {
ROUTE('GET /download/{id}/', download);
ROUTE('GET /photos/{id}/', photo);
};
function download(id) {
// true: the browser downloads the file with its stored name
this.filefs('documents', id, true);
}
function photo(id) {
this.imagefs('photos', id, function(image) {
image.resize(300, 300);
image.quality(85);
});
}The response has the stored content type, the Last-Modified header and the headers X-Size, X-Width and X-Height. A request with If-Modified-Since gets 304 Not Modified, and a request with a Range header gets a part of the file (206), so audio and video can be played from the storage. A file that does not exist or has expired gives 404.
checkmeta(meta) decides whether the file may be sent; return false to answer with 404:
function privatefile(id) {
var user = this.user;
this.filefs('documents', id, false, null, null, function(meta) {
return meta.custom && meta.custom.user === user.id;
});
}imagefs() processes the image with GraphicsMagick (or ImageMagick, see default_image_converter) and caches the result in the temporary folder, so the processing runs once per URL. The same methods exist on the response object as res.filefs() and res.imagefs(), for routes that work with req and res.
Uploaded files
Every file in controller.files has the method fs(storage, id, [custom], [expire], [callback]). It saves the uploaded file into the storage with its original file name:
exports.install = function() {
ROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);
};
function upload() {
var self = this;
var output = [];
self.files.wait(function(file, next) {
file.fs('documents', UID(), function(err, meta) {
!err && output.push({ id: meta.id, name: meta.name, size: meta.size });
next();
});
}, function() {
self.json(output);
});
}Changing and removing files
var fs = FILESTORAGE('documents');
fs.rename(id, 'new-name.pdf'); // changes the stored name
fs.move(id, newid); // changes the ID
fs.remove(id); // removes one file
fs.clean(); // removes expired files
fs.clear(); // removes all files (also drop())copy(id, path, [callback]) writes the content of a file to a path on the disk, and clone(id, [newid], [callback]) makes a copy of a file inside the storage under a new ID.
// Export to a folder: the file keeps its stored name
fs.copy(id, PATH.temp(), function(err, meta) {
console.log('Saved', meta.name);
});
// A second copy under a new ID
fs.clone(id, UID(), function(err, meta) {
console.log(meta.id);
});Listing and maintenance
browse() returns a NoSQL query builder over files.log, so you filter, sort and page the files like any other NoSQL query:
FILESTORAGE('photos').browse().where('ext', 'png').sort('date_desc').take(20).callback(function(err, files) {
console.log(files);
});count(callback)returns the number and total size of files fromfiles.logand updatesfs.totalandfs.size.browse2(),stream()andcount2()read the files on the disk instead offiles.log.rebuild()createsfiles.logagain from the files on the disk.backup(filename)writes all files into one backup file andrestore(filename)replaces the content of the storage with a backup.