How to exit a .JS process so it returns a StdOut value to AHK?

Viewed 202

I have a NodeJS script that is launched by an AutoHotKey script. I need this NodeJS script to return a specific value when exiting, so it can be retrieved and used by the AHK script. I am able to get the value returned by the process directly in my AHK script, but it's not the wanted one.

How do I make my process return a specific value?

So far, I tried using

process.exit(myValue); and

process.exitCode = myValue; and

process.stdout.write(myValue) but none of this works.

Here is my AHK script (which works fine) :

RunWait, C:\path_to_node\node.exe C:\path_to_script\index.js,,, output
MsgBox, %output%
2 Answers

Your output is only the Process ID (PID). You need to run your .js in a WSH wrapper, and your .js needs to return StdOut as follows:

Here is the AHK "secret sauce" RunWaitStdOut:

MsgBox % RunWaitStdOut("C:\path_to_script\index.js")

RunWaitStdOut(command)
{
    shell := ComObjCreate("WScript.Shell")
    exec := shell.Exec(ComSpec " /c node " command)
    return exec.StdOut.ReadAll() 
}

And in the meantime, the end of your .js should have something like the following generating the StdOut:

    process.stdout.write("The Result this javascript returns to AHK is " + myValue);

And remember, StdOut is a string, so if your myValue is a number or such, you may need the toString() method (as OP noticed, per OP's comment):

    process.stdout.write( myValue.toString() );

Hth,

From the docs:

RunWait sets ErrorLevel to the program's exit code (a signed 32-bit integer). If UseErrorLevel is in effect and the launch failed, the word ERROR is stored.

So you can get the exit code via ErrorLevel:

RunWait, C:\path_to_node\node.exe C:\path_to_script\index.js
output := ErrorLevel
MsgBox, %output%

Note that the exit code is a 32-bit signed integer and is set to 1 if node encounters an error. If you need proper output, use stdout, as suggested by PGilm.

Related