Skip to content

Instantly share code, notes, and snippets.

@ericabell
Created August 13, 2017 16:41
Show Gist options
  • Save ericabell/55bb80726e41313914e7aad800c3d6ec to your computer and use it in GitHub Desktop.
Save ericabell/55bb80726e41313914e7aad800c3d6ec to your computer and use it in GitHub Desktop.
Read a series of numbers from the terminal, compute their sum when input stream closes
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: 'Enter numbers sep by newlines. Ctrl-d when done> \n'
});
let inputStack = [];
// display our prompt with instructions for the user
rl.prompt();
// every time user hits enter, the 'line' event fires
rl.on('line', (input) => {
// add their input to our stack
inputStack.push(Number(input));
}).on('close', () => { // ctrl-d closes the stream, add the numbers, clean up
console.log('The sum is: ' + inputStack.reduce( (sum,val) => {
return sum +val;
}, 0));
process.exit(0);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment