I'm using Duktape in embedded MCU. For test case i have: main.js file:
(function(){
test();
})();
test.js file:
(function test(){
print("func");
})
Both compiled as global default code and main.js is executed with duk_call(ctx, 0);
The problem is it throws error when calling a test() function.
I've also tried using just
function test() {
print("test");
}
in test.js code, but it does not work either.
What I understand is that both files have separate execution context. That is why function is inaccessible.
But what is the right way to split code into multiple files for Duktape?
P.S. I am aiming to avoid using global context, because in documentation it is said that accessing variables is slow this way, that's why main.js looks that way.
P.P.S. I'm sure that test() function is unreachable, but I don't know how to write js code so that everything works.
P.P.P.S print() is a C function that outputs to serial port of esp32 and it works. even main.js works without a test() function call.
Basically, what you want is file import functionality. You can implement that in two ways:
The second idea is what is used most and implements a well defined approach to include other files in your JS application. Duktape comes with an extra file that implements the
requirecommand, just like in Node.js. You only have to provide your own functions for resolving a module and to load it from disk (as duktape has not file I/O support).I implemented this approach in the MGA tool in MySQL Workbench. The duktape file for implementing node module handling is here. The function to resolve modules (which includes handling of nested
node_modulesfolders etc.) is implemented in the ScriptingContext class. The relevant part of it is this: