Skip to content

Instantly share code, notes, and snippets.

@pbkhrv
Created October 13, 2014 22:29
Show Gist options
  • Save pbkhrv/0d17c4c3f69e372cdcd0 to your computer and use it in GitHub Desktop.
Save pbkhrv/0d17c4c3f69e372cdcd0 to your computer and use it in GitHub Desktop.
reading all of stdin into a variable in NodeJS?
function readWholeStdin() {
process.stdin.resume();
process.stdin.setEncoding('utf8');
var buffer = '';
process.stdin.on('data', function(chunk) {
buffer += chunk;
});
var deferred = Q.defer();
process.stdin.on('end', function() {
deferred.resolve(buffer);
});
return deferred.promise;
}
// Usage example:
readWholeStdin().then(function(text) {
console.log(text);
});
@johandalabacka
Copy link

With promises

function readWholeStdin () {
  return new Promise((resolve) => {
    process.stdin.resume()
    process.stdin.setEncoding('utf8')
    let buffer = ''
    process.stdin.on('data', (chunk) => {
      buffer += chunk
    })
    process.stdin.on('end', () => {
      resolve(buffer)
    })
  })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment