This answer is fairly incomplete. Leave many things to the imagination.
The following code is not mine, but is also available in sof and solves the problem of implementing the modSearch function:
duk_ret_t mod_search(duk_context *ctx) {
/* Nargs was given as 4 and we get the following stack arguments:
* index 0: id
* index 1: require
* index 2: exports
* index 3: module
*/
char *src = NULL;
FILE *f = NULL;
const char *filename = "/home/user/benchmark/js_modules/mylib.js";
int rc, len;
// Pull Arguments
char *id = duk_require_string(ctx, 0);
printf("ID => %s \n", id);
rc = strcmp(id, "mylib");
if(rc == 0)
{
printf("Module found, loading... \n");
// Read File and calculate its size (as DUKtape examples)
f = fopen(filename, "rb");
fseek(f, 0, SEEK_END);
len = (int) ftell(f);
// Rewind
fseek(f, 0, SEEK_SET);
src = malloc(len);
fread(src, 1, len,f);
fclose(f);
duk_push_lstring(ctx, src, len);
free(src);
return 1;
}
// Error
return -1;
}
Then, we need a native-code C function to register the modSearch function:
/* Declaration */
void modSearch_register(duk_context *ctx) {
duk_get_global_string(ctx, "Duktape");
duk_push_c_function(ctx, mod_search, 4 /*nargs*/);
duk_put_prop_string(ctx, -2, "modSearch");
duk_pop(ctx);
}
Then the main code:
duk_context *ctx;
ctx = duk_create_heap_default();
if (!ctx) {
return 1;
}
duk_push_c_function(ctx, handle_print, 1);
duk_put_global_string(ctx, "print");
duk_module_duktape_init(ctx);
printf("top after init: %ld\n", (long) duk_get_top(ctx));
//call function defintion for require
modSearch_register(ctx);
/* We push to Duktape heap the JS file*/
push_file_as_string(ctx, argv[1]);
if (duk_peval(ctx) != 0) {
printf("Error peval: %s\n", duk_safe_to_string(ctx, -1));
goto finished;
}
duk_pop(ctx); /* pop result/error */
finished:
duk_destroy_heap(ctx);
The native c code print function can be obtained from duktape web page, for example:
static duk_ret_t handle_print(duk_context *ctx) {
printf("%s\n", duk_safe_to_string(ctx, 0));
return 0;
}