napi hello world

Posted LogiCoal

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了napi hello world相关的知识,希望对你有一定的参考价值。

目录下的文件

build-node-addon-api-with-cmake.node
CMakeLists.txt
hello.cc
hello.js
package.json

build-node-addon-api-with-cmake.nodenpm run install后生成的

npm i -D cmake-js bindings node-addon-api

cmake-js --version

CMakeLists.txt

cmake_minimum_required(VERSION 3.9)
cmake_policy(SET CMP0042 NEW)
set (CMAKE_CXX_STANDARD 11)

project (build-node-addon-api-with-cmake)
include_directories(${CMAKE_JS_INC})
file(GLOB SOURCE_FILES "hello.cc")
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})

# Include N-API wrappers
execute_process(COMMAND node -p "require(‘node-addon-api‘).include"
        WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
        OUTPUT_VARIABLE NODE_ADDON_API_DIR
        )
string(REGEX REPLACE "[
"]" "" NODE_ADDON_API_DIR ${NODE_ADDON_API_DIR})

target_include_directories(${PROJECT_NAME} PRIVATE ${NODE_ADDON_API_DIR})

# define NPI_VERSION
add_definitions(-DNAPI_VERSION=3)

hello.cc

#include <assert.h>
#include <node_api.h>

static napi_value Method(napi_env env, napi_callback_info info) {
  napi_status status;
  napi_value world;
  status = napi_create_string_utf8(env, "Hello, world!", 13, &world);
  assert(status == napi_ok);
  return world;
}

#define DECLARE_NAPI_METHOD(name, func)                                          { name, 0, func, 0, 0, 0, napi_default, 0 }

static napi_value Init(napi_env env, napi_value exports) {
  napi_status status;
  napi_property_descriptor desc = DECLARE_NAPI_METHOD("hello", Method);
  status = napi_define_properties(env, exports, 1, &desc);
  assert(status == napi_ok);
  return exports;
}

NAPI_MODULE(hello, Init)

hello.js

var addon = require(‘bindings‘)(‘build-node-addon-api-with-cmake‘);

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

package.json

{
  "name": "build-node-addon-api-with-cmake",
  "version": "0.0.0",
  "description": "Build N-API native addon with CMake and node-addon-api C++ wrapper.",
  "main": "hello.js",
  "private": true,
  "dependencies": {},
  "scripts": {
    "install": "cmake-js compile",
    "test": "node hello.js"
  },
  "devDependencies": {
    "bindings": "^1.2.1",
    "cmake-js": "^6.1.0",
    "node-addon-api": "^1.7.2"
  }
}

以上是关于napi hello world的主要内容,如果未能解决你的问题,请参考以下文章

6个变态的C语言Hello World程序 之 雷人的程序语言

Hello World代码

Hello World代码

怎么用maven写出hello world

第一行代码Hello,World!

hello.equals(hello)的代码值是多少?