简体   繁体   English

N_API 如何将 int 值参数发送到 Napi::CallbackInfo

[英]N_API How to send int value parameters to Napi::CallbackInfo

This My first node.js and n_api.这是我的第一个 node.js 和 n_api。 I have been using PHP/APACHI.我一直在使用 PHP/APACHI。 But I need the c++ library for my web And I decided to using n_api.但是我的 web 需要 c++ 库,我决定使用 n_api。 The problem is that the value sent by ajax is always 0 in c++.问题是ajax发送的值在c++中始终为0。 I don't know what is problem.我不知道有什么问题。 ex) I using a vscode.例如)我使用 vscode。

const testAddon = require('./build/Release/firstaddon.node');

var http = require('http');
var url = require('url');
var fs = require('fs');
const express = require('express');
const app = express();
bodyParser = require('body-parser');

var port = '1080';

app.use(bodyParser.json());         // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.post('/server', function(req, res){ 
    var responseData = {};
    responseData.pID = req.body.pID; 
    console.log(responseData.pID);              <<============= here, value is correct.
    const prevInstance = new testAddon.ClassExample(4.3);
    var value = prevInstance.getFile(responseData.pID);   
    console.log(value);
    res.json(responseData);
});

If ajax sends 2, console.log(responseData.pID) //2 appears.如果 ajax 发送 2,则出现 console.log(responseData.pID) //2。 It is normal.这是正常的。 Below is the classtest.cpp下面是classtest.cpp

Napi::Value ClassTest::GetFile(const Napi::CallbackInfo &info)
{
  Napi::Env env = info.Env();
  Napi::HandleScope scope(env);

  using namespace std;
  if (info.Length() != 1 || !info[0].IsNumber())
  {
    Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException();
  }   
  Napi::Number file_id = info[0].As<Napi::Number>();
  int num = this->actualClass_->openFile(file_id);                   <<== here, file id

  return Napi::Number::New(info.Env(), num);
}

And ActualClass.cpp Files showing problems.并且 ActualClass.cpp 文件显示问题。

int ActualClass::openFile(int id)
{
  ifstream fin;  
  cout << id << endl;                  <<============================ here, always '0'

  filename += to_string(id) += ".txt";
  fin.open(filename.c_str(), ios_base::in | ios_base::binary);

  if (fin.is_open())
  {
    while (fin.read((char *)&sdo, sizeof(sdo)))
    {
      cout << setw(20) << sdo.name << ":"
           << setprecision(0) << setw(12) << sdo.width
           << setprecision(2) << setw(6) << sdo.height
           << setprecision(4) << setw(6) << sdo.size << endl;
      slist.push_back(sdo);
    }
    fin.close();       
  }
  else if (!fin.is_open())
  {
    cerr << "can't open file " << filename << ".\n";
    exit(EXIT_FAILURE);
  }

  return sdo.size;
}

Only files 1 to 4 are prepared.仅准备文件 1 到 4。 But, the argument value entering the function is always 0. Result is "can't open file 0.txt".但是,输入 function 的参数值始终为 0。结果是“无法打开文件 0.txt”。 How can I solve it?我该如何解决?

Napi::Number file_id = info[0].As<Napi::Number>();

I know here it is converted to an int value that can be handled by C++.我知道这里它被转换为可以由 C++ 处理的 int 值。 Is there anything else I don't know?还有什么我不知道的吗? Thanks for reading.谢谢阅读。

You need to cast it to the number with the help of the Napi::Number::Int32Value call.您需要借助Napi::Number::Int32Value调用将其转换为数字。 (You can also use Napi::Number::Int64Value for bigger numbers) Try this. (对于更大的数字,您也可以使用Napi::Number::Int64Value )试试这个。

int file_id = info[0].ToNumber().Int32Value();

Also unrelated to the question, but worth mentioning that when you are doing ThrowAsJavaScriptException() the actual C++ code keeps executing, you better return undefined to avoid nasty bugs.也与问题无关,但值得一提的是,当您执行ThrowAsJavaScriptException()实际 C++ 代码继续执行时,您最好返回 undefined 以避免讨厌的错误。

  if (info.Length() != 1 || !info[0].IsNumber())
  {
    Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException();
    return Env.Undefined();
  } 

A more clean way will be to enable the CPP exceptions and just throw the error in that place.一种更简洁的方法是启用 CPP 异常并在该位置抛出错误。

  if (info.Length() != 1 || !info[0].IsNumber())
  {
    throw Napi::TypeError::New(env, "Number expected");
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM