使用neon 开发nodejs addon
备注:开发使用的是mac 系统,需要安装rust nodejs 、python2.7 Xcode
1. 安装neon
npm install -g neon-cli
2. 创建简单项目
neon new firstaddon (会有提示进行输入即可)
3. 项目结构
├── README.md
├── lib
│ └── index.js
├── native
│ ├── Cargo.toml
│ ├── build.rs
│ └── src
│ └── lib.rs
└── package.json
说明:
pakcage.json 比较简单,主要是使用neon-cli 进行构建
{
"name": "firstaddon",
"version": "0.1.0",
"description": "",
"main": "lib/index.js",
"author": "dalongrong <1141591465@qq.com>",
"license": "MIT",
"dependencies": {
"neon-cli": "^0.1.22"
},
"scripts": {
"install": "neon build"
}
}
native 为一个简单的rust 项目,主要是进行node addon 的暴露
native/src/lib.rs 主要代码
#[macro_use]
extern crate neon;
use neon::vm::{Call, JsResult};
use neon::js::JsString;
fn hello(call: Call) -> JsResult<JsString> {
let scope = call.scope;
Ok(JsString::new(scope, "hello node").unwrap())
}
register_module!(m, {
m.export("hello", hello)
});
lib 目录进行node addon调用
lib/index.js
var addon = require('../native');
console.log(addon.hello());
4. 构建
npm install || yarn run install
node lib/index.js
5. 参考资料
https://www.neon-bindings.com/
https://www.npmjs.com/package/@dalongrong/firstaddon