Node.js C ++插件:如何在Node.js 10中通过N-API和V8创建JS Date对象

时间:2019-03-22 20:02:46

标签: node.js node.js-addon

napi_create_date函数从11.11.0版本开始出现在Node.js中。 https://nodejs.org/api/n-api.html#n_api_napi_create_date

仅使用N-API和V8 API可以在Node.js 10.15.3上创建JS日期(从C ++生成)的哪些变通办法?

或者我可以从N-API获得V8隔离?

或者如何结合使用N-API和NAN创建Date并在napi_call_function中使用它?

我需要某种方法来为napi_call_function调用创建Date值(从C ++ double中创建)。

1 个答案:

答案 0 :(得分:1)

现在,我写了一个解决方法。 使用env->context()而不是v8::Isolate::GetCurrent()更为正确,但是napi_env是在src/js_native_api_v8.h中定义的,而~/.node-gyp/10.15.3/include/node中不存在,因此我没有找到一种快速使用env->context()的方法。

#include <v8.h>

// This asserts v8::Local<> will always be implemented with a single
// pointer field so that we can pass it around as a void*.
static_assert(sizeof(v8::Local<v8::Value>) == sizeof(napi_value),
  "Cannot convert between v8::Local<v8::Value> and napi_value");

napi_status napi_create_date_by_v8(
    double time,
    napi_value* result
) {
  v8::Isolate* isolate = v8::Isolate::GetCurrent();

  v8::MaybeLocal<v8::Value> maybe_date = v8::Date::New(isolate, time);
  v8::Local<v8::Value> local = maybe_date.ToLocalChecked();
  *result = reinterpret_cast<napi_value>(*local);
  return napi_ok;
}