FiveTech Support Forums

FiveWin / Harbour / xBase community
Board index FiveWin for Harbour/xHarbour XD_JSHARBOUR: Execute JS from harbour
Posts: 6755
Joined: Wed Feb 15, 2012 08:25 PM
XD_JSHARBOUR: Execute JS from harbour
Posted: Tue Aug 05, 2025 02:18 PM
Bueno, despues de mucho tiempo persiguiendo el tema, tengo la primera version de XD_JSHARBOUR, que permite ejecutar codigo JS desde harbour, y poderlo integrar en cualquiera de nuestras aplicaciones, por ejemplo en nuestros servidores HBHTTP, con lo que ya no tenemos nada que envidiar a NODEJS, y SI, podremos hacer llamadas a funciones JS creadas por nosotros y viceversa, es decir, desde el codigo JS llamar a funciones Harbour ( estoy con ello )
Codigo Harbour
// ==================================================================
// Codigo Harbour
// ==================================================================

PROCEDURE Main()
    LOCAL cJS, cStatus
   LOCAL nJobs

    // 1. Inicializar
    cStatus := XD_JS_INIT()
    ? "JS_INIT:", cStatus
    IF !("ini" $ cStatus)
        Alert( "Salir" )
        RETURN
    ENDIF

   XD_JS_SET( "nombre", "Juan" )
   ? "XD_JS_SET hecho"
   ? XD_JS_EVAL( 'print("Hola", nombre)' )
   ? XD_JS_EVAL( 'nombre' )
   ? XD_JS_GET( "nombre" )

   ? XD_JS_EVAL( "10 + 20" )

   // 3. Usar JS_SET / JS_GET
    XD_JS_SET( "x", 42 )
    XD_JS_EVAL( 'print("x en JS =", x); y = x * 2;' )
    ? "y en Harbour =", XD_JS_GET( "y" )

    // 2. Evaluar código JS (multilínea con concatenación)
    cJS := 'print("Hola desde QuickJS!");' + hb_eol() + ;
           'let x = 42;' + hb_eol() + ;
           'print("x =", x);' + hb_eol() + ;
           'function prueba() {' + hb_eol() + ;
           '    print("Ejecutando prueba()");' + hb_eol() + ;
           '    let res = harbour_call();' + hb_eol() + ;
           '    print("Respuesta de Harbour:", res);' + hb_eol() + ;
           '}'

    cStatus := XD_JS_EVAL( cJS )
    ? "XD_JS_EVAL:", cStatus

    // 3. Llamar a la función JS
    cStatus := XD_JS_CALL_FUNCTION("prueba")
    ? "XD_JS_CALL_FUNCTION:", cStatus

    // 4. Probar Worker
    cJS := 'if (typeof Worker !== "undefined") {' + hb_eol() + ;
       '    const w = new Worker(function() {' + hb_eol() + ;
       '        postMessage("Worker iniciado");' + hb_eol() + ;
       '        setTimeout(() => {' + hb_eol() + ;
       '            postMessage("Timeout en worker");' + hb_eol() + ;
       '            close(); // Cierra el worker' + hb_eol() + ;
       '        }, 100);' + hb_eol() + ;
       '    });' + hb_eol() + ;
       '    w.onmessage = function(e) { print("Worker:", e.data); };' + hb_eol() + ;
       '    // Opcional: guardar w en global para poder w.terminate() después' + hb_eol() + ;
       '    globalThis.activeWorker = w;' + hb_eol() + ;
       '} else {' + hb_eol() + ;
       '    print("Worker no disponible");' + hb_eol() + ;
       '}'

    cStatus := XD_JS_EVAL( cJS )
    ? "XD_JS_EVAL (Worker):", cStatus
    inkey( 1.0 )
    // Terminar workers activos
    XD_JS_EVAL( 'if (globalThis.activeWorker) { globalThis.activeWorker.terminate(); print("Worker terminado"); }' )
    // 5. Procesar eventos pendientes
    inkey( 1.0 )
    DO WHILE (nJobs := XD_JS_EXECUTE_PENDING()) > 0
        inkey(1.0)
    ENDDO
    // 6. Liberar
    ? XD_JS_FREE()
    inkey( 0 )
    WAIT
RETURN
Resultado:

Evidentemente la idea es no necesitar entorno grafico ( no usar webview por ejemplo )
Cristobal Navarro

Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo

El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces
Posts: 6755
Joined: Wed Feb 15, 2012 08:25 PM
Re: XD_JSHARBOUR: Execute JS from harbour
Posted: Tue Aug 05, 2025 02:43 PM
Cristobal Navarro

Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo

El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces
Posts: 6983
Joined: Fri Oct 07, 2005 07:07 PM
Re: XD_JSHARBOUR: Execute JS from harbour
Posted: Wed Aug 06, 2025 06:13 AM

Dear Cristóbal,

thank you for your work on XD_JSHARBOUR – it looks like a truly exciting step forward for all of us working with Harbour.

Since I wasn’t entirely sure what it could be used for, I asked ChatGPT – and I found the explanation very helpful. I’d like to share it here in case others are also wondering what exactly your new library makes possible.

What is XD_JSHARBOUR?

This library lets you run JavaScript code directly from Harbour, without needing a graphical environment (no webview, no browser). That makes it perfect for:

Console applications

Microservices

Server-side logic (e.g. with HBHTTP)

You can:

Call JS functions from Harbour

Pass variables between Harbour and JS

Evaluate inline JavaScript code (even multiline)

Run JS workers and background tasks

What’s it useful for?

With XD_JSHARBOUR, you can:

Dynamically evaluate formulas or rules (e.g. amount > 1000)

Execute JS logic from configuration files or databases

Use modern JS features like JSON, Map, Set, async/await

Reuse logic written for frontend/web in your backend

Create plugin-like scripting capabilities in Harbour applications

It feels a bit like a lightweight JavaScript engine embedded into Harbour – a powerful alternative to Node.js, but integrated into your existing EXE or service.

Thanks again, Cristóbal – I’m looking forward to seeing what the community builds with this.

Maybe this will open the door for more hybrid or scriptable Harbour apps in the future!

Thanks again. Best regards, Otto

Posts: 6755
Joined: Wed Feb 15, 2012 08:25 PM
Re: XD_JSHARBOUR: Execute JS from harbour
Posted: Wed Aug 06, 2025 01:54 PM

Dear Otto

Thank you so much

Cristobal Navarro

Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo

El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces
Posts: 6755
Joined: Wed Feb 15, 2012 08:25 PM
Re: XD_JSHARBOUR: Execute JS from harbour
Posted: Wed Aug 06, 2025 10:54 PM
Cristobal Navarro

Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo

El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces

Continue the discussion