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