Sandpack/nodebox-runtime

Exit not sent on successful runCommand; also no way to get return value of runCommand except through console.log

nyvyn opened this issue · 2 comments

nyvyn commented

I have a simple case where I'd like to execute code in Nodebox, and see the return value from the file.

            const {Nodebox} = await import("@codesandbox/nodebox");
            const runtime = new Nodebox({
                // Provide a reference to the <iframe> element in the DOM
                // where Nodebox should render the runtime.
                iframe: runtimeFrame,
            });

            // Establish a connection with the runtime environment.
            await runtime.connect();

            // Populate the in-memory file system of Nodebox
            await runtime.fs.init({
                "package.json": JSON.stringify({
                    name: "code-evaluator",
                }),
                "index.js": "console.log('hello world'),
            });

            const shell = runtime.shell.create();

            // Listen for console and send that back to the server.
            shell.stdout.on("data", async (data) => {
                console.log(data);
            });

            // Exit is sent if there is an error parsing the file.
            await shell.on("exit", async (_exitCode, error: Error) => {
                if (error) console.log(error);
            });

            await shell.runCommand("node", ["index.js"]);

A couple of notes:

  • shell.on("exit") is never called in this case. Only if there's a parsing error of index.js.
  • There seems to be no way to get the results from index.js except through listening to stdout.on("data)".

Follow-on questions:

  • Is there a way to get a reliable "exit" called even on successful execution of the command/index.js example?
  • And is there an alternative to getting the return value (for example, if index.js returned a value, that's lost since there's no way to capture that result).

The exit behaviour is currently expected behaviour as we'd have to reimplement the entire event loop of node, which was out of scope for nodebox to make this work. It is mentioned in the limitations in the readme. Calling process.exit(x) or throwing an error synchronously is the only way to actually exit a process

For returning a value the only way is the stdout listener. This is by design as we see nodebox as a new process.

nyvyn commented

Okay, thank you much.