15

How do you include another script file inside a .js script file in v8?
There's the <script> tag in HTML but how can it be done inside a v8 embedded program?

the_drow
  • 18,571
  • 25
  • 126
  • 193

2 Answers2

25

You have to add this functionality manually, here is how I did it:

Handle<Value> Include(const Arguments& args) {
    for (int i = 0; i < args.Length(); i++) {
        String::Utf8Value str(args[i]);

        // load_file loads the file with this name into a string,
        // I imagine you can write a function to do this :)
        std::string js_file = load_file(*str);

        if(js_file.length() > 0) {
            Handle<String> source = String::New(js_file.c_str());
            Handle<Script> script = Script::Compile(source);
            return script->Run();
        }
    }
    return Undefined();
}

Handle<ObjectTemplate> global = ObjectTemplate::New();

global->Set(String::New("include"), FunctionTemplate::New(Include));

It basically adds a globally accessible function that can load and run a javascript file within the current context. I use it with my project, works like a dream.

// beginning of main javascript file
include("otherlib.js");
postfuturist
  • 22,211
  • 11
  • 65
  • 85
  • Looks like V8 was updated since this answer was posted. You now need Functiontemplate's ->GetFunction() accessor in the call to 'Set': e.g. FunctionTemplate::New(Include)->GetFunction() – Joe Wood May 28 '13 at 19:09
  • 1
    With the latest v8 as of today (Dec 17,2013), v8::Argument no longer exists (has v8::internal::Argument thou). So the v8::Argument& in the function arg declaration has to be changed to v8::FunctionCallbackInfo&. – yoshi Dec 17 '13 at 04:26
  • Hi @yoshi, the v8 engine was updated again and there seems to be many other things that I should do to run this code. I posted a question [here](https://stackoverflow.com/questions/64979842/how-can-i-include-another-js-file-file-in-todays-v8), can you help me out? – calvin Nov 24 '20 at 03:31
  • Hi@calvin, sorry but I can't help you. It's been eons of years since I worked on v8. Now I don't even (want to) touch it. Good luck! – yoshi Nov 24 '20 at 06:52
2

If you're using Node.js or any CommonsJS compliant runtime, you can use require(module); There's a nice article about it at http://jherdman.ca/2010-04-05/understanding-nodejs-require/

Petah
  • 45,477
  • 28
  • 157
  • 213
guigouz
  • 1,211
  • 1
  • 13
  • 18
  • that link is broken again. I did a quick google and couldn't find it based on the title and presumed author. – xaxxon Jan 07 '16 at 06:10
  • 2
    https://github.com/jherdman/jherdman.github.com/blob/master/2010-04-05/understanding-nodejs-require/index.html – nitely Mar 08 '16 at 21:41