使用N-API将数据流式传输到Node.js C ++插件 [英] Streaming data into a Node.js C++ Addon with N-API

查看:466
本文介绍了使用N-API将数据流式传输到Node.js C ++插件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为NodeJS构建C ++插件,我想将数据从C ++异步流传输到Node.我找到了这篇文章, https://nodeaddons.com/但是,将数据流式传输到一个节点js-c-addon/中;我想使用N-API而不是NAN.

I am building a C++ addon for NodeJS and I want to stream data asynchronously from C++ to Node. I have found this article, https://nodeaddons.com/streaming-data-into-a-node-js-c-addon/, however; I want to use the N-API instead of NAN.

我一直在搜索NodeJS文档和示例,并在寻找其他资源和示例,但是没有遇到任何资源向我展示如何实现这一目标.这是我第一次为NodeJS编写C ++插件.

I have been searching through the NodeJS docs and examples as well as looking for other resources and examples but have not come across a resource to show me how I can accomplish this. This is my first time writing a C++ addon for NodeJS.

一个可以帮助我入门的示例是一个使用N-API每秒将虚拟字符串发送给Node的插件,而Node会将字符串打印到控制台.

An example that would help me get started would be an addon that uses the N-API to send a dummy string every second to Node and Node would print the string to the console.

推荐答案

这是一个基于EventEmitter概念的代码段,该代码段模拟从本机层(C/C ++)读取传感器并将数据推送到Node.js(JavaScript)层.在此示例中,我们使用 node-addon-api,这是N-API的仅标头C ++包装器.在此示例中,我们使用了for循环(只有五个Itinatins),实际上,它可能是一个无限循环,不断读取传感器输出并将数据推送到JS层.本机层可以决定何时将其从传感器收集的数据报告给JS层. JS将接收订阅事件的异步数据.

Here is a snippet based on EventEmitter concept, which simulates reading of sensors from native layer (C/C++) and push the data to Node.js (JavaScript) layer. In this example we are using node-addon-api, a header-only C++ wrapper to N-API. Here for this example we have used a for loop (with only five iteratins), in reality it could be an infinite loop continuously reading sensors outputs and pushing the data to JS layer. The native layer can decide when to report the data it got collected from sensors to the JS layer. The JS will receive the data asynchronous for the subscribed events.

#include <napi.h>
#include <thread>

Napi::Value CallEmit(const Napi::CallbackInfo &info)
{
    char buff1[128];
    char buff2[128];
    int  sensor1 = 0;
    int  sensor2 = 0;

    Napi::Env env = info.Env();

    Napi::Function emit = info[0].As<Napi::Function>();
    emit.Call(  {Napi::String::New(env, "start")}  );

    for (int i = 0; i < 5; i++)
    {
        // Let us simulate some delay for collecting data from its sensors
        std::this_thread::sleep_for(std::chrono::seconds(2));

        sprintf(buff1, "sensor1 data %d ...", ++sensor1);

        emit.Call( { Napi::String::New(env, "sensor1"),
                   Napi::String::New(env, buff1 ) } );

        // Let, sensor 2 data is reported half the rate as sensor1
        if (i % 2)
        {
            sprintf(buff2, "sensor2 data %d ...", ++sensor2);
            emit.Call({ Napi::String::New(env, "sensor2"),
                       Napi::String::New(env, buff2) });
        }
    }

    emit.Call( {Napi::String::New(env, "end")} );
    return Napi::String::New( env, "OK" );
}

模块注册代码段是

#include <napi.h>

Napi::Object Init( Napi::Env env, Napi::Object exports )
{
  exports.Set(Napi::String::New(env, "callEmit"), Napi::Function::New(env, CallEmit));
  return exports;
}

NODE_API_MODULE( myncpp1, Init )

编译上面的本机代码,一旦成功构建,则可以运行以下node.js JavaScript代码进行测试.

Compile the above native code and once it is successfully built then you can run the following node.js JavaScript code to test it.

'use strict'

const EventEmitter = require('events').EventEmitter
const addon = require('bindings')('myncpp1')

// General theme of EventEmitter is: notify me when it is ready

function Main() {
    const emitter = new EventEmitter()

    emitter.on('start', () => {
        console.log( '### Sensor reading started ...');
    })

    emitter.on('sensor1', (evt) => {
        // This module will be called as on when the
        // sensor1 data available for consuming from JS
        console.log(evt);
    })

    emitter.on('sensor2', (evt) => {
        console.log(evt);
    })

    emitter.on('end', () => {
        console.log('### Sensor reading Ended');
    })

    addon.callEmit( emitter.emit.bind(emitter) )
}

Main();

该代码段应产生以下输出.

The code snippet should produce the following output.

### Sensor reading started ...
sensor1 data 1 ...
sensor1 data 2 ...
sensor2 data 1 ...
sensor1 data 3 ...
sensor1 data 4 ...
sensor2 data 2 ...
sensor1 data 5 ...
### Sensor reading Ended

这篇关于使用N-API将数据流式传输到Node.js C ++插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆