Neon is a library and toolchain that makes it possible to create native Node modules using Rust. This is similar to what is possible with C and C++, but with the additional benefits brought by Rust safety guarantees.

Neon strives to make creating Node.js module straightforward. Once you have installed the Neon package from npm and the Rust toolchain, you can use neon new <project-name> to create a skeleton Node module that embeds a Cargo.toml file and a Rust source file including a sample hello function:

<project-name>/
├── .git ignore
├── README.md
├── lib/
│   └── index.js
├── native/
│   ├── Cargo.toml
│   └── src/
│       └── lib.rs
└── package.json

You can add any Rust dependencies you need to Cargo.toml and layout your code as you prefer. You can export a Rust function so it can be used in a Node program in two steps. First, you register the function using:

register_module!(mut m, {
    m.export_function("myFunction", thread_count)
});

Then, you export it from lib/index.js:

const addon = require('../native');
module.exports = addon.myFunction;

When your code is ready, you can build the Node module with:

neon build --release

As straightforward as this appears, you should anyway pay special attention to behaving as a good citizen in the Node environment. In particular, any Rust function you export should be of a specific type:

fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> {
...
}

#rust #node #web-development #programming #developer

Neon Enables Embedding Rust Code in Node.js Apps
2.25 GEEK