Skip to content

Commit

Permalink
Handle non-TTY inputs better
Browse files Browse the repository at this point in the history
  • Loading branch information
isaacs committed Jun 14, 2012
1 parent f9b61af commit f68bf22
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions lib/read.js
Expand Up @@ -6,13 +6,19 @@ var buffer = ""
, StringDecoder = require("string_decoder").StringDecoder

function raw (mode) {
if (process.stdin.setRawMode) {
if (process.stdin.isTTY) {
process.stdin.setRawMode(mode)
}
return
}
// old style
try {
process.stdin.setRawMode(mode)
} catch (e) {
tty.setRawMode(mode)
}
} catch (e) {}
}


function read (opts, cb) {
if (!cb) cb = opts, opts = {}

Expand All @@ -27,6 +33,7 @@ function read (opts, cb) {
// switching into raw mode is a little bit painful.
// avoid if possible.
var r = silent || num ? rawRead : normalRead
if (r === rawRead && !process.stdin.isTTY) r = normalRead

if (timeout) {
cb = (function (cb) {
Expand Down Expand Up @@ -88,6 +95,11 @@ function normalRead (def, timeout, silent, num, cb) {
if (i !== 0) val = val.substr(i)
}

// hack. if we get the number of chars, just pretend there was a delim
if (num > 0 && val.length >= num) {
val = val.substr(0, num) + "\n" + val.substr(num)
}

// buffer whatever might have come *after* the delimter
var delimIndex = val.indexOf("\n")
if (delimIndex !== -1) {
Expand Down

0 comments on commit f68bf22

Please sign in to comment.