const fs = require('fs');
const FileSystemInFile = require('@brightsign/filesysteminfile');
var fsif;
var fd;
open()
.then(function(fileDescriptor) {
fd = fileDescriptor;
return write(fd);
})
.then(function(bytes) {
console.log(`${bytes} written to new file`);
return close(fd);
})
.then(function() {
// Create FileSystemInFile using the backing file
fsif = new FileSystemInFile('/storage/sd/usbstore');
return format();
})
.then(function() {
return mount();
})
.then(function() {
/* This is where you can actually do stuff with the mounted filesystem. */
// Unmount the mounted file after 10 seconds
setTimeout(function() {
return unmount();
}, 10000);
})
.catch(function(error) {
console.log(JSON.stringify(error));
});
// Create a writable file for the file system
function open() {
return new Promise(function(resolve, reject) {
fs.open('/storage/sd/usbstore', 'w', function(error, fd) {
if (error) reject(error);
resolve(fd);
});
});
};
// Write a buffer allocating 1GB of disk space for the file
function write(fd) {
return new Promise(function(resolve, reject) {
fs.write(fd, Buffer.alloc(1), 0, 1, (1024*1024*1024) - 1, function(error, bytesWritten) {
if (error) reject(error);
resolve(bytesWritten);
});
});
};
// Close the created file
function close(fd) {
return new Promise(function(resolve, reject) {
fs.close(fd, function(error) {
if (error) reject(error);
resolve();
});
});
};
// Format the file system
function format() {
return new Promise(function(resolve, reject) {
fsif.format("exfat")
.then(function() {
console.log('Filesystem formatted');
resolve();
})
.catch(function(error) {
reject(error);
});
});
};
// Mount the filesystem internally
function mount() {
return new Promise(function(resolve, reject) {
fsif.mount()
.then(function(mount_point) {
console.log('Filesystem mounted' + mount_point);
resolve();
})
.catch(function(error) {
reject(error);
});
});
};
// Unmount filesystem from internal mount point. Only can unmount a mounted file
function unmount() {
return new Promise(function(resolve, reject) {
fsif.unmount()
.then(function() {
console.log('Filesystem unmounted');
resolve();
})
.catch(function(error) {
reject(error);
});
});
}; |