Skip to content

Instantly share code, notes, and snippets.

@tahoeRobbo
Forked from mhart/test1.js
Last active September 25, 2015 17:59
Show Gist options
  • Save tahoeRobbo/f48940415ceeaae0a4fd to your computer and use it in GitHub Desktop.
Save tahoeRobbo/f48940415ceeaae0a4fd to your computer and use it in GitHub Desktop.
stdin/stdout pipe in node.js
process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function solveMeFirst(a, b) {
return a+b;
}
function main() {
// write your code here.
// call `readLine()` to read a line.
// use console.log() to write to stdout
var a = parseInt(readLine());
var b = parseInt(readLine());;
var res = solveMeFirst(a, b);
console.log(res);
}
// So this is short and easier
process.stdin.resume()
process.stdin.on('data', function(data) { process.stdout.write(data) })
process.stdout.on('error', function(err) {
if (err.code === 'EPIPE') return process.exit()
process.emit('error', err)
})
// But is this more "correct"?
process.stdin.resume()
process.stdin.on('data', function(data) { process.stdout.write(data) })
process.stdout.on('error', function epipeFilter(err) {
if (err.code === 'EPIPE') return process.exit()
// If there's more than one error handler (ie, us), then the error won't be bubbled up anyway
if (process.stdout.listeners('error').length <= 1) {
process.stdout.removeAllListeners() // Pretend we were never here
process.stdout.emit('error', err) // Then emit as if we were never here
process.stdout.on('error', epipeFilter) // Then reattach, ready for the next error!
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment