Worker thread postMessage() vs command line command

360 Views Asked by At

I recently learned about Worker threads in Node JS. I was trying to create a worker thread to run Stockfish chess engine in node js.

The npm package I am using for this is called stockfish. I tried using node-stockfish before this but it was not installing with npm as it was using an older version of the type definition for the "AbortSignal" variable apparently causing compatibility issues.

For the current npm package that I am using even though I was able to install it successfully, I could find very little documentation on how to use it. So I tried out a few ideas.

import { Worker } from "worker_threads";

const engine = new Worker("./node_modules/stockfish/src/stockfish.js")
engine.on('message', (data) => console.log(data))
engine.postMessage('position startpos move e2e4 e7e5')
engine.postMessage('go movetime 3000')

Here I tried to run the stockfish.js as a worker thread and send commands to it with the postMessage() function. This however did not work and it gave the following output:

worker.js received unknown command undefined
position startpos move e2e4 e7e5
worker.js received unknown command undefined
go movetime 3000

But I know these commands are valid commands if I run the same js from the command line like so: As you can see the same commands work when I run the js file from the command line

It might be because I am using the flags --experimental-wasm-threads and --experimental-wasm-simd when I am running it from the command line. I found this command to run it from the little documentation that was present. But I don't know how to mention these flags when I run it through a worker thread.

Otherwise it could also be that I don't understand how worker threads work yet and postMessage() is not the same as sending it a command from the command line.

Any help is greatly appreciated.

1

There are 1 best solutions below

0
On

I switched to using stockfish.wasm library instead. With this library I was able to achieve what I wanted and I don't need to use any worker threads for now. Maybe I can add this to a worker thread if required later. Here is a simple example:

const Stockfish = require("stockfish.wasm")

Stockfish().then((engine) => {
    engine.addMessageListener((output) => {
        console.log(output);
        // Do something with the output data here
    })
    engine.postMessage("uci");
    engine.postMessage("ucinewgame");
    engine.postMessage("position startpos");
    engine.postMessage("go depth 20");
});