You can use the Emscripten Filesystem API, for example, by calling FS.init in the PreRun function of the module, passing the user as standard input.
var Module = { preRun: function() { function stdin() { // Return ASCII code of character, or null if no input } var stdout = null; // Keep as default var stderr = null; // Keep as default FS.init(stdin, stdout, stderr); } };
The function is pretty low-level: you have to deal with one character at a time. To read some data from blob, you can do something like:
var data = new Int8Array([1,2,3,4,5]); var blob = new Blob([array], {type: 'application/octet-binary'}); var reader = new FileReader(); var result; reader.addEventListener("loadend", function() { result = new Int8Array(reader.result); }); var i = 0; var Module = { preRun: function() { function stdin() { if (if < result.byteLength { var code = result[i]; ++i; return code; } else { return null; } } var stdout = null;
Note (as you hinted), due to the asynchronous nature of the reader, there may be a race condition: the reader had to load before you could expect data on standard input. You may need to implement some mechanism to avoid this in the real case. Depending on your exact requirements, you can make Emscripten actually not call main() until you have data:
var fileRead = false; var initialised = false; var result; var array = new Int8Array([1,2,3,4,5]); var blob = new Blob([array], {type: 'application/octet-binary'}); var reader = new FileReader(); reader.addEventListener("loadend", function() { result = new Int8Array(reader.result); fileRead = true; runIfCan(); }); reader.readAsArrayBuffer(blob); var i = 0; var Module = { preRun: function() { function stdin() { if (i < result.byteLength) { var code = result[i]; ++i; return code; } else{ return null; } } var stdout = null; var stderr = null; FS.init(stdin, stdout, stderr); initialised = true; runIfCan(); }, noInitialRun: true }; function runIfCan() { if (fileRead && initialised) {
Note: is this a variant of my answer on Providing stdin for the emscripten HTML program? but with a focus on standard input and adding parts about transferring data from Blob.