ファイル
C++ は自身の標準ライブラリでファイルを読み書きします。Web では、ファイルはモジュールのファイルシステムにあり、JavaScript からもアクセスできます。
m.FS がそのファイルシステムです。main.js はメモリ上に置かれるフォルダー /memfs の下にファイルを書き、C++ はディスク上と同じように、std::ifstream と std::ofstream で同じパスを開きます。
/memfs の下のファイルは、ページが開いている間だけ残ります。再読み込み後も必要なブラウザーのアプリは /opfs の下に書きます。これには Web Worker が必要です。Node.js では、同じ C++ が実際のパスを開きます。詳しくはファイルを参照してください。
試してみる
JavaScript からさらに 2 行追加して、もう一度数えてみましょう。[■]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' }));