how to execute shell commands from duktape

383 Views Asked by At

I need to build a javascript engine (duktape or jerryscript) for a embedded device which should be capable of executing shell commands. how can this be achieved?

1

There are 1 best solutions below

2
Codesmith On

With duktape in C, you can easily create a native ECMAScript function and create a reference to it via the global object:

#include "duktape.h"

int main() {
    /* create heap */
    duk_context* heap = duk_create_heap(NULL,NULL,NULL,NULL,
                                        NULL); /* preferably, set an error callback here */

    /* push the native function on the stack */
    duk_push_c_function(ctx, /* heap context */
                        &native_js_shell, /* native function pointer */
                        1); /* accepted arguments */

    /* make this javascript function a property of the global object */
    duk_put_global_string(ctx, /* heap context*/
                          "shell"); /* function name in js */

    return 0;
}

/* Your native C function */
duk_ret_t native_js_shell(duk_context* ctx) {
    /* obtain the argument from javascript */
    const char* cmd = duk_safe_to_string(ctx, /* heap context */
                                         -1); /* position on stack */

    /* run the shell command, etc. */
    /* ... */
}

All the explanation for the duk_* functions can be found in the duktape API, but perhaps this gives you an idea of how it's structured.

p.s. Welcome to Stack Overflow! Your question may have been downrated since it pretty much requires someone to write all the code for you. In general, in the future, try to do the research on your own, and ask specific questions as you get stuck. :)