Skip to content

Is it possible to determine the type of an NAPI::Object in a non-global context? #764

@jschlight

Description

@jschlight

This question is related to an interesting issue raised on the node-sqlite3 project:

TryGhost/node-sqlite3#1355

The JavaScript code from the issue looks like:

const vm = require('vm');
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');

const contextObject = { db, console };

db.each('select ?', new Date(), console.log);
vm.runInNewContext("db.each('select ?', [new Date()], console.log);", contextObject);

The pertinent code using node-addon-api looks like:

bool OtherInstanceOf(Napi::Object source, const char* object_type) {
    if (strncmp(object_type, "Date", 4) == 0) {
        return source.InstanceOf(source.Env().Global().Get("Date").As<Function>());
    } else if (strncmp(object_type, "RegExp", 6) == 0) {
        return source.InstanceOf(source.Env().Global().Get("RegExp").As<Function>());
    }
    return false;
}

The code to determine if source is a Date object is failing apparently because source has been allocated outside the global context.

The author of the node-sqlite3 issue has identified the IsDate method as a way to address this issue. But is there another more general approach that would work to identify type of an NAPI::Object in a non-global context?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions