Module quickjs_runtime::features::console
source · Expand description
the console feature enables the script to use various cansole.log variants see also: MDN the following methods are available
- console.log()
- console.info()
- console.error()
- console.warning()
- console.trace()
The methods use rust’s log crate to output messages. e.g. console.info() uses the log::info!() macro so the console messages should appear in the log you initialized from rust
All methods accept a single message string and optional substitution values
e.g.
console.log('Oh dear %s totaly failed %i times because of a %.4f variance in the space time continuum', 'some guy', 12, 2.46)
will output ‘Oh dear some guy totaly failed 12 times because of a 2.4600 variance in the space time continuum’
The string substitution you can use are
- %o or %O Outputs a JavaScript object (serialized)
- %d or %i Outputs an integer. Number formatting is supported, for example console.log(“Foo %.2d”, 1.1) will output the number as two significant figures with a leading 0: Foo 01
- %s Outputs a string (will attempt to call .toString() on objects, use %o to output a serialized JSON string)
- %f Outputs a floating-point value. Formatting is supported, for example console.log(“Foo %.2f”, 1.1) will output the number to 2 decimal places: Foo 1.10
§Example
use quickjs_runtime::builder::QuickJsRuntimeBuilder;
use log::LevelFilter;
use quickjs_runtime::jsutils::Script;
simple_logging::log_to_file("console_test.log", LevelFilter::max())
.ok()
.expect("could not init logger");
let rt = QuickJsRuntimeBuilder::new().build();
rt.eval_sync(None, Script::new(
"console.es",
"console.log('the %s %s %s jumped over %i fences with a accuracy of %.2f', 'quick', 'brown', 'fox', 32, 0.512);"
)).expect("script failed");
which will result in a log entry like
[00:00:00.012] (7f44e7d24700) INFO the quick brown fox jumped over 32 fences with a accuracy of 0.51