util.types.isExternal(value)


如果值是原生的 External 值,则返回 true

原生的 External 值是特殊类型的对象,它包含用于从原生代码访问的原始 C++ 指针 (void*),并且没有其他属性。 此类对象由 Node.js 内部或原生插件创建。 在 JavaScript 中,它们是带有 null 原型的冻结对象。

#include <js_native_api.h>
#include <stdlib.h>
napi_value result;
static napi_value MyNapi(napi_env env, napi_callback_info info) {
  int* raw = (int*) malloc(1024);
  napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);
  if (status != napi_ok) {
    napi_throw_error(env, NULL, "napi_create_external failed");
    return NULL;
  }
  return result;
}
...
DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
...
const native = require('napi_addon.node');
const data = native.myNapi();
util.types.isExternal(data); // 返回 true
util.types.isExternal(0); // 返回 false
util.types.isExternal(new String('foo')); // 返回 false

有关 napi_create_external 的更多信息,请参阅 napi_create_external()

Returns true if the value is a native External value.

A native External value is a special type of object that contains a raw C++ pointer (void*) for access from native code, and has no other properties. Such objects are created either by Node.js internals or native addons. In JavaScript, they are frozen objects with a null prototype.

#include <js_native_api.h>
#include <stdlib.h>
napi_value result;
static napi_value MyNapi(napi_env env, napi_callback_info info) {
  int* raw = (int*) malloc(1024);
  napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result);
  if (status != napi_ok) {
    napi_throw_error(env, NULL, "napi_create_external failed");
    return NULL;
  }
  return result;
}
...
DECLARE_NAPI_PROPERTY("myNapi", MyNapi)
...
const native = require('napi_addon.node');
const data = native.myNapi();
util.types.isExternal(data); // returns true
util.types.isExternal(0); // returns false
util.types.isExternal(new String('foo')); // returns false

For further information on napi_create_external, refer to napi_create_external().