Connecting node.js to stdin/stdout

The context here is a UCI chess interface such that a Javascript chess engine running in node.js can communicate with standard chess UIs like Arena and Winboard via stdin/stdout.  But the code may be useful in other contexts too.

My own UCI interface (node.js and web worker compatible) can be found here in the lozUCI class and also some initialisation code (like that below) at the end of the file.

http://op12no2.me/toys/lozza/lozza.js

If you mine it for your own projects please attribute and link back here.

stdin

var nodefs = require('fs');

process.stdin.setEncoding('utf8');

process.stdin.on('readable', function() {
  var chunk = process.stdin.read();
  if (chunk !== null) {
    onmessage({data: chunk});
  }
});

process.stdin.on('end', function() {
  process.exit();
});

The UCI commands are then available in data.data in onmessage().  Note that more than one command can be present separated by \n and depending on OS also \r, so assume \n and filter out \r.  In my own experience null commands can be present \n\n, so watch out for those too.

stdout

var str = ''
... 
nodefs.writeSync(1, str + '\n');

The use of writeSync() is so that that the PV feedback displays in chess UIs like Arena and Winboard in real time.  If you write using async functions it appears all at once when the best move is sent back.

It’s useful to name the capture function onmessage() because that what web workers assume, thus it can be used in both web and node.js contexts.