WASM IDBFS 不持久

问题描述 投票:0回答:1

我有一个加载 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

然后我重新加载浏览器(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 实现中的错误吗?

这是我的 emscripten 版本:

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.

build wasm 是一个由 2 个方法组成的小程序。我在这个例子中没有使用它们。

在构建中我设置了以下参数:-std=c++11 --bind -lidbfs.js -s FORCE_FILESYSTEM=1

webassembly indexeddb
1个回答
0
投票

文档说:

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

© www.soinside.com 2019 - 2024. All rights reserved.