文件
C++ 用自己的标准库读写文件。在 Web 上,这些文件位于模块的文件系统中,JavaScript 也可以访问。
m.FS 就是这个文件系统。main.js 在 /memfs(保存在内存中的文件夹)下写入一个文件,然后 C++ 用 std::ifstream 和 std::ofstream 打开同一个路径,就像在磁盘上一样。
/memfs 下的文件只在页面存在期间保留。需要在重新加载后仍保留文件的浏览器应用,要写入 /opfs 下,这需要 Web Worker。在 Node.js 上,同样的 C++ 打开的是真实路径。详见文件。
试一试
从 JavaScript 再追加两行,然后重新计数。[■]native.h1#pragma once
#include <string>
// C++ opens files with its own library. On the web they live in
// the module's file system, which JavaScript reads and writes.
int countLines(const std::string &path);
void append(const std::string &path, const std::string &line);
[■]main.js2import {
initNative, countLines, append,
} from './native/native.h';
const m = await initNative();
const path = '/memfs/todo.txt';
await m.FS.writeFile(path, 'bind\nbuild\n');
await append(path, 'run');
console.log('lines:', await countLines(path));
console.log(await m.FS.readFile(path, { encoding: 'utf8' }));