• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <node.h>
2 #include <node_buffer.h>
3 #include <assert.h>
4 
5 namespace {
6 
7 using v8::Context;
8 using v8::Isolate;
9 using v8::Local;
10 using v8::MaybeLocal;
11 using v8::Object;
12 using v8::Script;
13 using v8::String;
14 using v8::Value;
15 
MakeBufferInNewContext(const v8::FunctionCallbackInfo<v8::Value> & args)16 inline void MakeBufferInNewContext(
17     const v8::FunctionCallbackInfo<v8::Value>& args) {
18   Isolate* isolate = args.GetIsolate();
19   Local<Context> context = Context::New(isolate);
20   Context::Scope context_scope(context);
21 
22   // This should throw an exception, rather than actually do anything.
23   MaybeLocal<Object> buf = node::Buffer::Copy(isolate, "foo", 3);
24   assert(buf.IsEmpty());
25 }
26 
RunInNewContext(const v8::FunctionCallbackInfo<v8::Value> & args)27 inline void RunInNewContext(
28     const v8::FunctionCallbackInfo<v8::Value>& args) {
29   Isolate* isolate = args.GetIsolate();
30   Local<Context> context = Context::New(isolate);
31   Context::Scope context_scope(context);
32 
33   context->Global()->Set(
34       context,
35       String::NewFromUtf8(isolate, "data").ToLocalChecked(),
36       args[1]).FromJust();
37 
38   assert(args[0]->IsString());  // source code
39   Local<Script> script;
40   Local<Value> ret;
41   if (!Script::Compile(context, args[0].As<String>()).ToLocal(&script) ||
42       !script->Run(context).ToLocal(&ret)) {
43     return;
44   }
45 
46   args.GetReturnValue().Set(ret);
47 }
48 
Initialize(Local<Object> exports,Local<Value> module,Local<Context> context)49 inline void Initialize(Local<Object> exports,
50                        Local<Value> module,
51                        Local<Context> context) {
52   NODE_SET_METHOD(exports, "runInNewContext", RunInNewContext);
53   NODE_SET_METHOD(exports, "makeBufferInNewContext", MakeBufferInNewContext);
54 }
55 
56 }  // anonymous namespace
57 
58 NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, Initialize)
59