Last active
March 6, 2019 20:59
-
-
Save op12no2/04cad531c535d36f9c3ff1663cebc68e to your computer and use it in GitHub Desktop.
Connecting node.js to stdin/stdout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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