Why does `require` cause an error in Duktape?

duktape, javascript

Solution

Duktape requires (no pun intended) you to provide a Module Search function in order to preserve portability. However, implementing one is a pretty simple and straight-forward task even if you have little experience in Duktape. A very simple but fully functional Module Search function would be:

Duktape.modSearch = function(id) {
    return readFileAsString(id);
}

This would allow you to call `require(filename)` from the Duktape Javascript environment with a filename as parameter and use it as your module. A more advanced function would handle errors or maybe search multiple paths and folders.

To use the `require()` function, you now have to create a C/C++ function that handles reading a file and returning it's content as a string and bind this function to the Duktape engine (Example for this is on the Duktape home page). Now call this function definition from the Duktape runtime (For example using `duk_eval_string(ctx, "Duktape.modSearch = ...");`) and you should be able to call `require()`.

Problem

I am using Duktape to embed JavaScript, but using `require` always causes an error: ``` int main(){ duk_context *ctx = duk_create_heap_default(); duk_peval_file(ctx, "example.js"); printf("file load err %s", duk_safe_to_string(ctx, -1)); duk_destroy_heap(ctx); } ``` example.js ``` var mylib = require("mylib") print (mylib.hello) ``` mylib.js ``` exports.hello = "Hello" ``` Error: file load err TypeError: not callable Stack dump says: duk_js_call.c:682 require native strict preventsyield eval example.js:1 preventsyield

Original source