RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
怎么编写nodejsc++插件

这篇文章主要介绍“怎么编写nodejs c++插件”,在日常操作中,相信很多人在怎么编写nodejs c++插件问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么编写nodejs c++插件”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

成都创新互联服务项目包括马关网站建设、马关网站制作、马关网页制作以及马关网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,马关网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到马关省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!

环境

1 ubuntu18.04。
2 安装nodejs v12和npm install node-gyp -g。 

写代码

写一个测试的例子。test.cc

// hello.cc using N-API
#include 

namespace demo {

napi_value Method(napi_env env, napi_callback_info args) {
  napi_value greeting;
  napi_status status;

  status = napi_create_string_utf8(env, "world", NAPI_AUTO_LENGTH, &greeting);
  if (status != napi_ok) return nullptr;
  return greeting;
}

napi_value init(napi_env env, napi_value exports) {
  napi_status status;
  napi_value fn;

  status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
  if (status != napi_ok) return nullptr;

  status = napi_set_named_property(env, exports, "hello", fn);
  if (status != napi_ok) return nullptr;
  return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, init)

}  // namespace demo
 

binding.gyp

{
  "targets": [
    {
      "target_name": "test",
      "sources": [ "./test.cc" ]
    }
  ]
}
 

然后执行npm init。内容如下

{
  "name": "test-addons",
  "version": "1.0.1",
  "description": "",
  "main": "./build/Release/test.node",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "install": "node-gyp rebuild"
  },
  "author": "",
  "license": "ISC",
  "gypfile": true
}
 

我们主要看和插件相关的两个配置

"main": "./build/Release/test.node",
"gypfile": true
 

main定义了插件的入口,因为我们没有为用户提供js的api。而是直接提供.node文件,所以这里定义的路径为插件的路径。gypfile标记这个包是一个c++插件,用户在使用npm安装这个包的时候,就会执行node-gyp rebuild,针对用户系统环境,生成对应的二进制代码。有些文章介绍了需要在scripts的值里加入"install": "node-gyp rebuild",npm文档说了如果包下面有.gyp文件的话,默认就会执行这个rebuild操作。

"scripts":{"install": "node-gyp rebuild"}
If there is a binding.gyp file in the root of your package and you have not defined an install or preinstall script, npm will default the install command to compile using node-gyp.

一切准备就绪,我们可以执行npm publish发布了(记得先登录npm)。 

测试

我们首先安装这个包。npm install test-addons --unsafe-perm,然后写代码测试一下。

var addon = require("test-addons/build/Release/test");
console.log(addon.hello());                        
 

我们发现,这样显然很麻烦。所以我们最好还是在包里为用户提供js模块的接口。我们在包里增加index.js

var addon = require("./build/Release/test");
module.exports = addon;                    
 

修改测试代码

var addon = require("test-addons");
console.log(addon.hello());

到此,关于“怎么编写nodejs c++插件”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!


分享题目:怎么编写nodejsc++插件
本文网址:http://sczitong.cn/article/jgpijd.html