linux下 开发node插件的步骤

 

系统环境ubuntu18.04

一、首先安装node

https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions-enterprise-linux-fedora-and-snap-packages

以上是各个版本下的安装链接

1、

Node.js v8.x:

# Using Ubuntu
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs

# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_8.x | bash -
apt-get install -y nodejs

检验:node -v  

注意:如果是ubuntu12.04的,安装nodejs会出现各种问题,建议升级版本

二、安装node-gyp

https://github.com/nodejs/node-gyp#installation

1、npm install -g node-gyp

2、node-gyp --python /path/to/python2.7

 

三、下面就是插件开发的步骤

实例 Hello World

1、

首先,创建 hello.cc 文件:

// hello.cc
#include <node.h>

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void Method(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}

void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "hello", Method);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, init)

}  // namespace demo

 2、

当源代码已被编写,它必须被编译成二进制 addon.node 文件。 要做到这点,需在项目的顶层创建一个名为 binding.gyp 的文件,它使用一个类似 JSON 的格式来描述模块的构建配置。 该文件会被 node-gyp(一个用于编译 Node.js 插件的工具)使用。

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "hello.cc" ]
    }
  ]
}

 3、测试

当构建完成时,二进制插件就可以在 Node.js 中被使用,通过 require() 构建后的 addon.node 模块:

// hello.js
const addon = require('./build/Release/addon');

console.log(addon.hello());
// 打印: 'world'

 构建addon模块步骤

(1)node-gyp configure --debug

(2)node-gyp build 

就会在build/Debug/下面生成一个addon.node

然后执行,node  hello.js执行结果如下  world

表示该模块成功生成

最后不能忘记环境变量 

$ export npm_config_devdir=/tmp/.gyp
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值