0

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?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Jack Dunsk
  • 91
  • 1
  • 11
  • It's not the problem, but it doesn't make sense to pass an `async` function as a callback to Node.js-style callback API functions. They don't do anything with the promise the `async` function returns. – T.J. Crowder Jul 31 '19 at 09:11
  • @T.J.Crowder Oh sorry, the async is used in other, promise-based parts of the code inside this function, but I removed them as they are irrelevant for this question. – Jack Dunsk Jul 31 '19 at 09:15
  • It still doesn't make sense to use an `async` function in a Node.js callback (unless you wrap the entire thing in `try`/`catch` so you catch all errors, to prevent getting an unhandled rejection). – T.J. Crowder Jul 31 '19 at 09:17

0 Answers0