NodeJS C++插件开发(二) - 示例代码hello world

534 阅读2分钟

NodeJS C++插件开发(二) - 示例代码hello world


如需转载请标明出处
QQ技术交流群:129518033

文章目录

发布时间:2021-06-20
更新时间:2021-06-20

典型场景:
- hello world
- 带参数的函数
- callback回调函数
- 异步编程基础
- 第三方库的调用
- restful接口测试C++插件性能
环境:
OS:windows 10 64bit
NodeJS:v14.16.0
node-gyp: v7.1.2( 前置python 3.6.8和vs2019)
cmake-js: v6.1.0 (前置cmake 3.18.1和vs2019)

相关阅读:
NodeJS C++插件开发(一) - 简介

前言

本文将以hello world的代码示例,介绍如何编写、编译及运行NodeJS C++插件。

上一篇文章中提到NodeJS C++插件的实现方式主要有原生方式、NAN和N-API方式,本文中主要以N-API为主来进行介绍。其他实现方式可以到node-webdev项目查看。

1. 编写和编译NodeJS C++插件

源码目录结构:

$ tree
.
+--- addon.cpp
+--- binding.gyp
+--- CMakeLists.txt
+--- index.js

1.1 编写NodeJS C++插件源码addon.cpp

addon.cpp

#include <node_api.h>

napi_value helloMethod(napi_env env, napi_callback_info info)
{
    napi_value result;

    napi_create_string_utf8(env, "hello world", NAPI_AUTO_LENGTH, &result);

    return result;
}

napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc = {"hello", 0, helloMethod, 0, 0, 0, napi_default, 0};

    napi_define_properties(env, exports, 1, &desc);

    return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)

1.2 编写NodeJS C++插件源码构建配置文件

NodeJS C++插件的源码构建方式主要有node-gyp和cmake.js。

1.2.1 node-gyp方式binding.gyp

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

1.2.2 cmake-js方式CMakeLists.txt

cmake_minimum_required(VERSION 2.8)

project(addon)

message(STATUS "operation system is ${CMAKE_SYSTEM}")

add_definitions(-std=c++11)
#add_compile_options(-g)

# 设置头文件路径
include_directories(${CMAKE_JS_INC})
include_directories(.)

# 源文件列表
file(GLOB SOURCE_FILES addon.cpp)

# 生成.node文件
add_library(${PROJECT_NAME} SHARED ${SOURCE_FILES} ${CMAKE_JS_SRC})

# 设置输出文件后缀
set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "" SUFFIX ".node")

# 设置库依赖
target_link_libraries(${PROJECT_NAME} ${CMAKE_JS_LIB})

1.3 编译NodeJS C++插件

1.3.1 node-gyp方式

  • 安装node-gyp( 前置python 3.6.8和vs2019)
$ npm i -g node-gyp
$ node-gyp -v
v7.1.2
  • 编译NodeJS C++插件(debug版本和vs2019)
$ node-gyp configure build --debug

1.3.2 cmake-js方式

  • 安装cmake-js(前置cmake 3.18.1)
$ npm i -g cmake-js
$ cmake.js -v
[  'D:\\Program Files\\nodejs\\node.exe',  'C:\\Users\\dev\\AppData\\Roaming\\npm\\node_modules\\cmake-js\\bin\\cmake-js',  '--version']
6.1.0
  • 编译NodeJS C++插件(debug版本)
$ cmake-js configure build --debug

2. 编写NodeJS JavaScript测试代码

index.js

'use strict';

const addon = require('bindings')('addon');

console.log(addon.hello()); // 'hello world'

3. 运行结果

$ node index.js
hello world

License

License under CC BY-NC-ND 4.0: 署名-非商业使用-禁止演绎


Reference:

  1. gitee.com/itas109/nod…