Created
March 21, 2017 03:33
-
-
Save ConorOBrien-Foxx/177d3fa2daf447d0366e600a5665db68 to your computer and use it in GitHub Desktop.
works except for when there aren't any lines to be read
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
// modified from https://gist.github.com/espadrine/172658142820a356e1e0 | |
var fs = require('fs'); | |
// Returns a buffer of the exact size of the input. | |
// When endByte is read, stop reading from stdin. | |
function getStdin(endByte) { | |
var BUFSIZE = 256; | |
var buf = new Buffer(BUFSIZE); | |
var totalBuf = new Buffer(BUFSIZE); | |
var totalBytesRead = 0; | |
var bytesRead = 0; | |
var endByteRead = false; | |
var fd = process.stdin.fd; | |
// Linux and Mac cannot use process.stdin.fd (which isn't set up as sync). | |
var usingDevice = false; | |
try { | |
fd = fs.openSync('/dev/stdin', 'rs'); | |
usingDevice = true; | |
} catch (e) {} | |
for (;;) { | |
try { | |
bytesRead = fs.readSync(fd, buf, 0, BUFSIZE, null); | |
// Copy the new bytes to totalBuf. | |
var tmpBuf = new Buffer(totalBytesRead + bytesRead); | |
totalBuf.copy(tmpBuf, 0, 0, totalBytesRead); | |
buf.copy(tmpBuf, totalBytesRead, 0, bytesRead); | |
totalBuf = tmpBuf; | |
totalBytesRead += bytesRead; | |
// Has the endByte been read? | |
for (var i = 0; i < bytesRead; i++) { | |
if (buf[i] === endByte) { | |
endByteRead = true; | |
break; | |
} | |
} | |
if (endByteRead) { break; } | |
} catch (e) { | |
if (e.code === 'EOF') { break; } | |
throw e; | |
} | |
if (bytesRead === 0) { break; } | |
} | |
if (usingDevice) { fs.closeSync(fd); } | |
return totalBuf; | |
} | |
function getline() { | |
return getStdin('\n'.charCodeAt(0)).toString('utf-8'); | |
} | |
console.log('First line: "' + getline() + '"'); | |
console.log('Second line: "' + getline() + '"'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment