Writing and Reading contents to a File asynchronously

40 views
Skip to first unread message

Aitha Tarun

unread,
Oct 12, 2022, 2:07:01 AM10/12/22
to emscripten-discuss
Hi,
Is it possible to write contents to a file at an indefinite time from javascript and read those contents in C code after some amount of time and continue this process?

For example, if I write some content from javascript to a shared file at a time "t" and want to read that contents in C code at "t+1" time and clear those contents from the shared file, and again the javascript code will write the contents at "t+2" time and want to read that contents in C code at "t+3" time.

Means will the compiled C code (emscripten web assembly)  and our own Javascript code can run asynchronously? 

Javascript Code:

Module.noInitialRun = true;

Module.onRuntimeInitialized = ()=>
{
    console.log("Initialized");

    const stream = Module.FS.open('./events.txt', 'a+');

    window.addEventListener
    (
        'keyup',
        (ev) =>
        {
            if(ev.key === 'p')
            {
                console.log("Writing");
                const output = 'p';

                const enc = new TextEncoder();
                enc.encode(output);

                const data = enc.encode(output);

                Module.FS.write(stream, data, 0, data.length);
            }
        }
    );

    Module.callMain();
}

C Code:

#include <stdio.h>
#include <string.h>

int main()
{
    FILE* ptr;
    char str[50];

    ptr = fopen("./events.txt", "r");

    if (NULL == ptr)
    {
        printf("Unable to open events file\n");
        return -1;
    }

    printf("File contents : \n");

    while (fgets(str, 50, ptr) != NULL)
    {
            printf("%s\n", str);
    }

    // Perform some operations here
    // And again execute the above reading code after some time
   
    return 0;
}

Thomas Lively

unread,
Oct 13, 2022, 12:22:15 PM10/13/22
to emscripte...@googlegroups.com
If the C code and the JS code are running on different threads, this should work fine. If they are running on the same thread, then the C will need to return to the event loop to let the JS run at some point. You can use `emscripten_async_call` to schedule more C code to run again in the future after the original C code has returned to the event loop.

--
You received this message because you are subscribed to the Google Groups "emscripten-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to emscripten-disc...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/emscripten-discuss/f0a1a6ae-7c2a-4a97-9124-b5025dcaedd3n%40googlegroups.com.

Aitha Tarun

unread,
Oct 13, 2022, 2:35:38 PM10/13/22
to emscripten-discuss
Ok thanks for the information 
Reply all
Reply to author
Forward
0 new messages