1

I would like to run JS code from within the C++ node.js addon.

What i tried is this:

// addon C++ snipplet (just added to the simple example addon code
static NAN_METHOD(RunScript) {
    MyObject* obj = ObjectWrap::Unwrap<MyObject>(info.Holder());

    v8::Local<v8::String> s = info[0]->ToString();

    v8::Local<UnboundScript> script = Nan::New<UnboundScript>(s).ToLocalChecked();
    MaybeLocal<v8::Value> result = Nan::RunScript(script);

    info.GetReturnValue().Set(result.ToLocalChecked());
}

When i load this addon from JS, I can run simple scripts:

// JS code
var OB = require('./build/Debug/objectwraphandle.node')
var obj1 = new OB.MyObject(42)
var returns = obj1.runScript("2+3");
console.log("returned: " + returns);
// ==> writes out 5, as expected

But when i write this:

// JS code
var OB = require('./build/Debug/objectwraphandle.node')
var obj1 = new OB.MyObject(42)
var returns = obj1.runScript("var express = require('express');")

I get:

FATAL ERROR: v8::ToLocalChecked Empty MaybeLocal.
1: node::Abort() [node]
2: 0x565373d379b1 [node]
3: v8::Utils::ReportApiFailure(char const*, char const*) [node]
4: v8::MaybeLocal<v8::UnboundScript>::ToLocalChecked()
      [/home...objectwraphandle.node]
5: MyObject::RunScript(Nan::FunctionCallbackInfo<v8::Value> const&)
      [/home/.../objectwraphandle.node]
6: 0x7f493bc79dc6 [/home/.../objectwraphandle.node]
7: v8::internal::FunctionCallbackArguments::Call(void (*)
       (v8::FunctionCallbackInfo<v8::Value> const&)) [node]

What am I doing wrong here? Why may my JS snipplets that I want to run not contain "require"? Calls to "console.log" work fine. (If there are other limitations, I did not see them so far)

GerritP
  • 33
  • 4
  • My guess: `require()` is [passed in as an argument](https://nodejs.org/api/modules.html#modules_the_module_wrapper) to the module wrapper that Node "folds" around each module (including any plain JS file that it runs), so it's not a global like `console`. You somehow need to pass a reference to `require` to the C++ code. – robertklep Oct 18 '18 at 14:56
  • With your comment, I found this: https://stackoverflow.com/questions/17581830/load-node-js-module-from-string-in-memory Maybe this helps me... Thanks! – GerritP Oct 18 '18 at 15:13

0 Answers0