larvitfiles
Installation
npm i larvitfiles;
Usage
Load library
const FileLib = require('larvitfiles');
const db = require('larvitdb');
const fs = require('fs');
db.setup(conf);
const fileLib = new FileLib({
db: db,
storagePath: '/tmp/larvitfiles',
log: new (new (require('larvitutils'))).Log(),
prefix: '/dbfiles/'
});
await fileLib.ready();
Add file from disk
fs.readFile('/some/file.txt', function (err, data) {
let file;
if (err) throw err;
const file = await fileLib.save({
slug: 'slug/foo/bar.txt',
data: data,
metadata: {metadata1: 'metavalue1', metadata2: ['multiple', 'values']},
});
console.log('file saved with uuid: ' + file.uuid);
console.log('metadata: ' + JSON.stringify(file.metadata));
console.log('slug: ' + file.slug);
});
Update file on disk
By default .save() will not accept a duplicate slug without also supplying a matching uuid.
If the below script is ran when a file with the slug "slug/foo/bar.txt" already exists in the database, this will throw an error.
const file = await fileLib.save({
slug: 'slug/foo/bar.txt',
data: Buffer.from('någe')
});
To overwrite the existing file, on the same uuid, use option "updateMatchingSlug":
const file = await fileLib.save({
slug: 'slug/foo/bar.txt',
data: Buffer.from('någe'),
updateMatchingSlug: true
});
Get file from storage
const file = await fileLib.get({slug: 'slug/foo/bar.txt'});
const file = await fileLib.get({uuid: 'uuid of file'});
console.log('file saved with uuid: ' + file.uuid);
console.log('metadata: ' + JSON.stringify(file.metadata));
console.log('slug: ' + file.slug);
Remove a file from storage
fileLib.rm(await fileLib.uuidFromSlug('slog/foo/bar.txt'));
console.log('File is now removed from storage');
List files in storage
List all files
const files = await fileLib.list();
console.log(result);
Filter list based on metadata
const options = {
filter: {
metadata: {
foo: 'bar',
zoo: true
},
operator: 'and'
}
};
const files = await fileLib.list(options);
console.log(files);
And if several values should exist on a single metadata do this:
const options = {
filter: {
metadata: {
foo: ['bar', 'baz']
}
}
};
const files = await fileLib.list(options);
console.log(files);
});