1#include <node.h> 2#include <node_buffer.h> 3#include <assert.h> 4 5namespace { 6 7using v8::Context; 8using v8::Isolate; 9using v8::Local; 10using v8::MaybeLocal; 11using v8::Object; 12using v8::Script; 13using v8::String; 14using v8::Value; 15 16inline 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 27inline 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 49inline 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 58NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, Initialize) 59