-
-
Save tahoeRobbo/f48940415ceeaae0a4fd to your computer and use it in GitHub Desktop.
stdin/stdout pipe in node.js
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
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); | |
} |
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
// 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) | |
}) |
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
// 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