//Include a script file into current context //Raise javascript exception if load failed v8::Handle _BeaScript::include( const Arguments& args ) { boost::filesystem::path parentPath = scriptPath.parent_path(); //v8::String::Utf8Value fileName(args[i]); std::string fileName = bea::Convert::FromJS(args[0], 0); //Add the script path to it boost::filesystem::path absolutePath = parentPath / fileName; if (!absolutePath.has_extension() && !boost::filesystem::exists(absolutePath)) absolutePath.replace_extension(".js"); HandleScope scope; v8::Handle result; v8::Handle source; if (boost::filesystem::exists(absolutePath)) source = ReadFile(absolutePath.string().c_str()); if (source.IsEmpty()){ std::stringstream s; s << "Could not include file " << absolutePath.string(); return v8::ThrowException(v8::Exception::Error(v8::String::New(s.str().c_str()))); } //Run the included script in a new context v8::Persistent newContext = v8::Context::New(); newContext->SetSecurityToken(securityToken); //Inspired by node_script.js - copy all main context's global properties to the new context Handle module = createModule(absolutePath.string()); v8::Local keys = args.This()->GetPropertyNames(); for (uint32_t i = 0; i < keys->Length(); i++) { v8::Handle key = keys->Get(i)->ToString(); v8::Handle value = args.This()->Get(key); newContext->Enter(); newContext->Global()->Set(key, value); newContext->Exit(); } v8::Handle retVal; { v8::Context::Scope ctxScope(newContext); newContext->Global()->Set(v8::String::NewSymbol("module"), module); //global.exports = module.exports newContext->Global()->Set(v8::String::NewSymbol("exports"), module->Get(v8::String::NewSymbol("exports"))); result = execute(source, bea::Convert::ToJS(absolutePath.string().c_str())->ToString()); if (!result.IsEmpty()){ retVal = newContext->Global()->Get(v8::String::NewSymbol("module")); if (!retVal->IsUndefined() && retVal->IsObject()){ retVal = retVal->ToObject()->Get(v8::String::NewSymbol("exports")); } //If module.exports is undefined, return whatever the included script returns if (retVal->IsUndefined()) retVal = result; } else retVal = v8::ThrowException(v8::Exception::Error(v8::String::New(lastError.c_str()))); } newContext.Dispose(); return scope.Close(retVal); }