How do I read a user-specified file in an emscripten compiled library?

c, emscripten, filesystems, node.js

Solution

If you want compile this file directly into library you can use `--preload-file` or `--embed-file` option. Like this:

emcc main.cpp -o main.html --preload-file /tmp/my@/home/caiiiycuk/test.file

After that in C you can open this file normally:

fopen("/home/caiiiycuk/test.file", "rb")

Or you can use emscripten JavaScript fs-api, for example with AJAX:

$.ajax({
    url: "/dataurl",
    type: 'GET',
    beforeSend: function (xhr) {
        xhr.overrideMimeType("text/plain; charset=x-user-defined");
    },
    success: function( data ) {
        Module['FS_createDataFile']("/tmp", "test.file", data, true, true);
    }
});

After that you can open this file from C. Also it is not best way to pass data into C code, you can pass data directly in memory, read about this.

Problem

I'm currently working on a file parsing library in C with emscripten compile support. It takes a file path from the user where it reads the binary file and parses it. I understand that emscripten doesn't support direct loading of files, but instead uses a virtual filesystem. Is there any way to load the file at the given path into the virtual filesystem so that the emscripten compiled C lib can read it? I'm looking for solutions for both NodeJS and in the browser.

Original source

Related problems