Skip to content

Instantly share code, notes, and snippets.

@op12no2
Last active March 6, 2019 20:59
Show Gist options
  • Save op12no2/04cad531c535d36f9c3ff1663cebc68e to your computer and use it in GitHub Desktop.
Save op12no2/04cad531c535d36f9c3ff1663cebc68e to your computer and use it in GitHub Desktop.
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:-
// https://github.com/op12no2/lozza
// 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment