How to capture stdout of js_of_ocaml toplevel

248 views Asked by At

I have this js_of_ocaml code that takes a string and executes it (assuming the string is OCaml code):

let () = JsooTop.initialize ()

let execute code =
  let code = Js.to_string code in
  let buffer = Buffer.create 100 in
  let formatter = Format.formatter_of_buffer buffer in
  JsooTop.execute true formatter code;
  Js.string (Buffer.contents buffer)

(* Usage: *)
let () =
    let ret_val_1 = execute "let x = 5;;" in
    let ret_val_2 = execute "print_int (x * x);;" in  (* 25 appears in the browser console. *)
    print_endline ret_val_1;  (* Prints: "val x : int = 5" *)
    print_endline ret_val_2   (* Prints: "- : unit = ()" *)

25 appears in the browser console after the code is run, because of the print_int (x * x) line. I want to use the output (i.e. 25) in the DOM instead of having it appear in the browser console. How can I capture the standard output produced by the printing functions of js_of_ocaml? i.e. How can I get 25 from within the code above?

1

There are 1 answers

0
Julien On BEST ANSWER

You can connect the output using Sys_js.set_channel_flusher stdout f where f is a function that you should define which takes the string to be printed and append it somewhere in your DOM.

If you look at the Toplevel example distributed with Js_of_ocaml, that's what they do. The Formatter is plugged to a dummy /dev/null and they set a "channel flusher" that append the text to an "output" div encapsulated a div whose class is stdout, the stderr channel flusher do the same but with class stderr, enabling the stderr to be printed in red.