I am trying to write a buffer to a file in localStorage using BrowserFS.
This is a simplified version of the code I am executing:
// Simple function to create a buffer that is filled with value
function createFilledBuffer(size, value) {
const b = Buffer.alloc(size)
b.fill(value)
return b
}
// Configure localStorage FS instance
BrowserFS.configure({
fs: "LocalStorage"
}, function (e) {
if (e) {
console.error('BrowserFS error:', e);
return;
}
// Get BrowserFS's fs module
const fs = BrowserFS.BFSRequire('fs');
const fileName = '/demo.txt';
fs.exists(self.fileName, async (exists) => {
let file;
// Open the file
if (!exists) {
file = fs.openSync(self.fileName, 'w+')
} else {
file = fs.openSync(self.fileName, 'r+')
}
// Write to file -> here is the problem?
// Fill first two "sectors" of the file with 0s
const sector = 4096;
// Write first sector
const bw1 = fs.writeSync(file, createFilledBuffer(sector, 0), 0, sector, 0)
// Write second sector
const bw2 = fs.writeSync(file, createFilledBuffer(sector, 0), 0, sector, sector)
console.log('Bytes written to file: ', bw1, bw2)
});
});
The output in the console is: Bytes written to file: 4096 4096
, suggesting that it had successfully written the data but when I try to get the file size of '/demo.txt' using fs.stat
, it is still 0 bytes large.
Later in my code I also try to write a buffer with real data (not just 0) into the file at specific locations, like:
const buffer = ...;
const bytesWritten = fs.writeSync(file, buffer, 0, buffer.length, 7 * sector)
which will also tell me it has written buffer.length
bytes (=481), but looking at fs.stat, the file still contains 0 bytes.
What do I have to do to successfully write the bytes to the file?