Add alternative reading via shell on the environment which don't support interactively reading.

This commit is contained in:
anseki 2014-06-27 10:06:29 +09:00
parent a108b7f9fd
commit 5a3c2d7ce4
4 changed files with 31 additions and 6 deletions

View file

@ -1,4 +1,4 @@
Copyright (c) 2013 anseki
Copyright (c) 2014 anseki
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation

View file

@ -65,6 +65,7 @@ try {
```
## Release History
* 2014-06-27 v0.2.3 Add alternative reading via shell on the environment which don't support interactively reading.
* 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.

View file

@ -2,7 +2,7 @@
* readlineSync
* https://github.com/anseki/readline-sync
*
* Copyright (c) 2013 anseki
* Copyright (c) 2014 anseki
* Licensed under the MIT license.
*/
@ -14,9 +14,19 @@ var promptText = '> ',
fs = require('fs'),
stdin = process.stdin,
stdout = process.stdout,
buffer = new Buffer(BUF_SIZE);
buffer = new Buffer(BUF_SIZE),
useShell = true;
var _readlineSync = function(display) {
function _readlineShell() {
// Win isn't supported by sync-exec v0.3.2
var command = /* require('os').platform() === 'win32' ?
'cmd "' + __dirname + '\\read.bat' : */
'sh "' + __dirname + '/read.sh"',
resExec = require('sync-exec')(command); // instead of execSync (node v0.12+)
return resExec.status === 0 && !resExec.stderr ? (resExec.stdout + '') : false;
}
function _readlineSync(display) {
var input = '', rsize, err;
if (display) { stdout.write(display, encoding); }
@ -29,6 +39,14 @@ var _readlineSync = function(display) {
rsize = fs.readSync(stdin.fd, buffer, 0, BUF_SIZE);
} catch (e) {
if (e.code === 'EOF') { break; } // pipe
if (useShell) {
// Try reading via shell
input = _readlineShell();
if (typeof input === 'string') { break; }
}
// Give up...
if (e.code === 'EAGAIN') { // EAGAIN, resource temporarily unavailable
// util can't inherit Error.
err = new Error('The platform doesn\'t support interactive reading from stdin');
@ -46,7 +64,10 @@ var _readlineSync = function(display) {
stdin.pause();
return input.trim();
};
}
// for dev
exports.useShellSet = function(use) { useShell = use; };
exports.setPrompt = function(newPrompt) {
if (typeof newPrompt === 'string') {

View file

@ -1,7 +1,7 @@
{
"name": "readline-sync",
"description": "Synchronous Readline",
"version": "0.2.2",
"version": "0.2.3",
"homepage": "https://github.com/anseki/readline-sync",
"author": {
"name": "anseki"
@ -23,6 +23,9 @@
"engines": {
"node": ">= 0.8.0"
},
"dependencies": {
"sync-exec": "~0.3.2"
},
"keywords": [
"readline",
"synchronous",