DelSkayn / rquickjs

High level bindings to the quickjs javascript engine
MIT License
431 stars 58 forks source link

How to import `console` object in rquickjs? #309

Closed getong closed 2 months ago

getong commented 2 months ago

The code:

use rquickjs::{async_with, AsyncContext, AsyncRuntime};

#[tokio::main]
async fn main() {
  let rt = AsyncRuntime::new().unwrap();
  let ctx = AsyncContext::full(&rt).await.unwrap();

  async_with!(&ctx => |ctx| {
    if let Ok(res) = ctx.eval::<(), &str>("console.log(\"hello world\");") {
      println!("Result: {:?}", res);
    } else {
      println!("Failed to evaluate JavaScript code");
    }

    if let Ok(res) = ctx.eval::<i32, &str>("2 + 5") {
      println!("Result: {:?}", res);
    } else {
      println!("Failed to evaluate JavaScript code");
    }
  })
  .await;
}

The run result is

Failed to evaluate JavaScript code
Result: 7

I think console.log("hello world") is (), the unit type in rust. But it does not work here.

getong commented 2 months ago

It seems that, the console object does not import here. How can I import javascript console object here?

richarddd commented 2 months ago

There is no console. You have to build it yourself

DelSkayn commented 2 months ago

There is indeed no console object in rquickjs you will have to build it yourself.

Also note that if you call catch on the result from the trait CatchResultExt you will get the actual error returned by quickjs which would have told you that console didn't exist. By default exceptions are only stub, you will have to actually retrieve the error from the context to get the full error.

getong commented 2 months ago

Thanks