Skip to content

Instantly share code, notes, and snippets.

@kareniel
Last active March 11, 2024 15:25
Show Gist options
  • Select an option

  • Save kareniel/99f242f3f024afe5de3a216140dd3362 to your computer and use it in GitHub Desktop.

Select an option

Save kareniel/99f242f3f024afe5de3a216140dd3362 to your computer and use it in GitHub Desktop.
echo a string in neon (rust & node)

echo a string in neon (rust & node

starting from the hello_world demo:

  1. we are gonna need the to_string method. but items from traits can only be used if the trait is in scope so we need to add Value to our use statement.

use neon::js::JsString;

to

use neon::js::{JsString, Value};

  1. we need to store our argument and convert it to a string, so we need to add the following line after let scope = call.scope;:

let my_str = try!(try!(call.arguments.require(scope, 0)).to_string(scope)).value();

  1. the new method on JsString class takes a &str so we add a & before the name of the variable:

Ok(JsString::new(scope, "hello node").unwrap())

to

Ok(JsString::new(scope, &my_str).unwrap())

And that's it!

#[macro_use]
extern crate neon;

use neon::vm::{Call, JsResult};
use neon::js::{JsString, Value};

fn echo(call: Call) -> JsResult<JsString> {
    let scope = call.scope;
    let my_str = try!(try!(call.arguments.require(scope, 0)).to_string(scope)).value();

    Ok(JsString::new(scope, &my_str).unwrap())
}

register_module!(m, {
    m.export("echo", echo)
});
const addon = require('../native')
console.log(addon.echo('abc')) // 'abc'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment