IndexedDB WASM IDBFS不持久

o4tp2gmn  于 2023-09-28  发布在  IndexedDB
关注(0)|答案(1)|浏览(222)

我有一个加载wasm模块的HTML页面。我把这个JS代码添加到HTML中:

// Create a directory in IDBFS to store the file
FS.mkdir('/persistent');

// Mount IDBFS as the file system
FS.mount(IDBFS, {}, '/persistent');

// Define a function to write a string to a file in the persistent directory
function writeStringToFile(path, string) {
  var fd = FS.open(path, 'w+');
  FS.write(fd, string, 0, string.length, 0);
  FS.close(fd);
}

// Define a function to read a file from the persistent directory
function readStringFromFile(path) {
  var fd = FS.open(path, 'r');
  var buffer = new Uint8Array(FS.stat(path).size);
  FS.read(fd, buffer, 0, buffer.length, 0);
  var decoder = new TextDecoder('utf8');
  var data = decoder.decode(buffer);
  FS.close(fd);
  return data;
}

在此代码之后,我在浏览器控制台中执行以下代码:

// Sync the file system to IDBFS with persistence enabled
FS.syncfs(true, (err) => {
  if (err) {
    console.log('Error syncing file system:', err);
  } else {
    console.log('File system synced successfully with persistence enabled!');
  }
});

// Write a string to a file in the persistent directory
writeStringToFile('/persistent/myfile.txt', 'Hello, world!');
FS.readdir('/persistent') //Check File exists -> OK

然后我重新加载broser(F5)并在浏览器控制台中执行以下命令:

// Read the string back from the file after reloading the page
FS.syncfs(false, (err) => {
  if (err) {
    console.log('Error syncing file system:', err);
  } else {
    FS.readdir('/persistent') //Check File exists -> File doesn't exist.
    console.log('File system synced successfully with persistence disabled!');
    var data = readStringFromFile('/persistent/myfile.txt');
    console.log('Contents of file:', data);
  }
});

我看到在浏览器的IndexDB中创建了一个条目:$url/persistent/FILE_DATA
但我看不到myfile.txt。
我不明白这是怎么回事?这是wasm FS实现中的一个bug吗?
以下是我的版本:

emcc --version
emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 3.1.32 (eab98adf462c39f3c31d348331c4830bcaa36949)
Copyright (C) 2014 the Emscripten authors (see AUTHORS.txt)
This is free and open source software under the MIT license.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

构建wasm是一个由两个方法组成的小程序。我在这个例子中没有使用它们。
在构建中,我设置了以下参数:-std=c++11 --bind-lidbfs.js-s FORCE_FILESYSTEM=1

pxiryf3j

pxiryf3j1#

Documentation says:
populate(bool)- true使用来自文件系统的持久源的数据初始化Emscripten的文件系统数据,false将Emscripten的文件系统数据保存到文件系统的持久源。
所以你要做的恰恰相反:

FS.mkdir('/workdir');
FS.mount(FS.filesystems.IDBFS, {}, '/workdir')

FS.syncfs(true, (err) => {
  console.log(FS.readdir('/workdir'))
  const s = FS.analyzePath('/workdir/test')
  if (s.exists) {
    console.log(FS.readFile('/workdir/test', {encoding: 'utf8'}).toString())
  } else {
    FS.writeFile('/workdir/test', 'hello world')
    FS.syncfs(false, (err) => {
      console.log('saved to idbfs', FS.readdir('/workdir'))
    })
  }
})

当页面刷新时,将输出hello world。还要注意,默认情况下,syncfs参数是false,它将FS同步到IDBFS。

相关问题