forked from nodejs/node-addon-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_script.cc
More file actions
55 lines (43 loc) · 1.37 KB
/
run_script.cc
File metadata and controls
55 lines (43 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "napi.h"
using namespace Napi;
namespace {
Value RunPlainString(const CallbackInfo& info) {
Env env = info.Env();
return env.RunScript("1 + 2 + 3");
}
Value RunStdString(const CallbackInfo& info) {
Env env = info.Env();
std::string str = "1 + 2 + 3";
return env.RunScript(str);
}
Value RunJsString(const CallbackInfo& info) {
Env env = info.Env();
return env.RunScript(info[0].As<String>());
}
Value RunWithContext(const CallbackInfo& info) {
Env env = info.Env();
Array keys = info[1].As<Object>().GetPropertyNames();
std::string code = "(";
for (unsigned int i = 0; i < keys.Length(); i++) {
if (i != 0) code += ",";
code += keys.Get(i).As<String>().Utf8Value();
}
code += ") => " + info[0].As<String>().Utf8Value();
Value ret = env.RunScript(code);
Function fn = ret.As<Function>();
std::vector<napi_value> args;
for (unsigned int i = 0; i < keys.Length(); i++) {
Value key = keys.Get(i);
args.push_back(info[1].As<Object>().Get(key));
}
return fn.Call(args);
}
} // end anonymous namespace
Object InitRunScript(Env env) {
Object exports = Object::New(env);
exports["plainString"] = Function::New(env, RunPlainString);
exports["stdString"] = Function::New(env, RunStdString);
exports["jsString"] = Function::New(env, RunJsString);
exports["withContext"] = Function::New(env, RunWithContext);
return exports;
}