【发布时间】:2021-03-11 14:10:00
【问题描述】:
我一直在探索用 C/C++ 为 node.js 编写附加模块。到目前为止,我有一个简单的附加工作,我可以在 JavaScript 中调用附加功能,这非常简单。该例程称为 hello,它传递一个字符串,然后返回以 Hello 为前缀的相同字符串,两个单词之间有一个空格。
package.json:
{
"name": "test",
"version": "2.0.0",
"description": "test description",
"main": "index.js",
"gypfile": true,
"scripts": {
"build": "node-gyp rebuild",
"clean": "node-gyp clean"
},
"author": "Simon Platten",
"license": "ISC",
"devDependencies": {
"node-gyp": "^7.1.2"
},
"dependencies": {
"node-addon-api": "^3.1.0"
}
}
binding.gyp:
{
"targets":[{
"target_name": "test",
"cflags!": ["-fno-exceptions"],
"cflags_cc!": ["-fno-exceptions"],
"sources": ["cpp/main.cpp"],
"include_dirs": ["<!@(node -p \"require('node-addon-api').include\")"],
"libraries": [],
"dependencies": ["<!(node -p \"require('node-addon-api').gyp\")"],
"defines": ["NAPI_DISABLE_CPP_EXCEPTIONS"],
}]
}
main.cpp
/**
* File: main.cpp
* Notes:
* Work in progress for add on module for node.js 'test'
* History:
* 2021/03/11 Written by Simon Platten
*/
#include <napi.h>
#include <iostream>
#include <string>
/**
* Return "Hello " + user name passed back
*/
Napi::String hello(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
std::string strResult = "Hello ";
strResult += info[0].ToString();
return Napi::String::New(env, strResult);
}
/**
* Callback method when module is registered with Node.js
*/
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(
Napi::String::New(env, "hello"),
Napi::Function::New(env, hello)
);
return exports;
}
NODE_API_MODULE(test, Init);
index.js:
const test = require("./build/Release/test");
console.log(test.hello("Simon"));
这很好用,现在我想更冒险一点。我不确定这方面的正确术语,但例如,当在节点中使用套接字时,会有各种 on 回调或可以使用回调函数管理的事件。这正是我想从我的模块中实现的,模块将传递大量数据进行处理,当模块处理数据时,我将立即返回,并且当它完成并准备好用于我要发布的客户端时以 on 样式处理程序的形式向 node.js 发送通知。
怎么做?
【问题讨论】:
标签: c++ node.js node.js-addon