From 7bcbbe3ef8c4dbb4b255db55b5c3260e89076575 Mon Sep 17 00:00:00 2001 From: anseki Date: Wed, 18 Dec 2013 11:51:32 +0900 Subject: [PATCH] fixed #1 --- README.md | 14 ++++++++++++-- lib/readline-sync.js | 20 +++++++++++--------- package.json | 2 +- 3 files changed, 24 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 946aeaf..7ddf068 100644 --- a/README.md +++ b/README.md @@ -52,9 +52,19 @@ readlineSync.setPrompt(encoding) Set the encoding method of input (user's response) and output (`prompt`). Defaults to 'utf8'. ## Note -The your Node and OS may not support interactively reading from stdin. The stdin interfaces are different by platforms. +The your Node and OS may not support interactively reading from stdin. The stdin interfaces are different by platforms. +If in those platforms, an error is thrown. + +```js +try { + answer = readlineSync.question('What is your favorite food? :'); +} catch (e) { + console.error(e); + process.exit(1); +} +``` ## Release History - * 2013-12-18 v0.2.1 Error handle for the environment which don't support interactively reading from stdin. + * 2013-12-18 v0.2.2 Error handle for the environment which don't support interactively reading from stdin. * 2013-08-30 v0.2.0 Rewrite exporting methods. * 2013-08-29 v0.1.0 Initial release. diff --git a/lib/readline-sync.js b/lib/readline-sync.js index 02701cb..67e8110 100644 --- a/lib/readline-sync.js +++ b/lib/readline-sync.js @@ -17,26 +17,28 @@ var promptText = '> ', buffer = new Buffer(BUF_SIZE); var _readlineSync = function(display) { - var input = '', rsize; + var input = '', rsize, err; if (display) { stdout.write(display, encoding); } stdin.resume(); while (true) { rsize = 0; + try { rsize = fs.readSync(stdin.fd, buffer, 0, BUF_SIZE); } catch (e) { - if (e.code === 'EAGAIN') { - // Error: EAGAIN, resource temporarily unavailable - if (display) { stdout.write('\n', encoding); } // Next of prompt line. - console.error('Error: This machine don\'t support interactively reading from stdin.'); - process.exit(1); - } else if (e.code === 'EOF') { - break; + if (e.code === 'EOF') { break; } // pipe + if (e.code === 'EAGAIN') { // EAGAIN, resource temporarily unavailable + // util can't inherit Error. + err = new Error('The platform don\'t support interactively reading from stdin'); + err.errno = e.errno; + err.code = e.code; } - throw e; + if (display) { stdout.write('\n', encoding); } // Return from prompt line. + throw err || e; } + if (rsize === 0) { break; } input += buffer.toString(encoding, 0, rsize); if (/[\r\n]$/.test(input)) { break; } diff --git a/package.json b/package.json index 2ac2a02..20b9f11 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "readline-sync", "description": "Synchronous Readline", - "version": "0.2.1", + "version": "0.2.2", "homepage": "https://github.com/anseki/readline-sync", "author": { "name": "anseki"