readline-sync/lib/readline-sync.js

91 lines
2.2 KiB
JavaScript
Raw Normal View History

2013-08-29 12:55:23 +02:00
/*
* readlineSync
* https://github.com/anseki/readline-sync
*
* Copyright (c) 2014 anseki
2013-08-29 12:55:23 +02:00
* Licensed under the MIT license.
*/
'use strict';
2013-08-29 19:26:22 +02:00
var promptText = '> ',
encoding = 'utf8',
BUF_SIZE = 256,
fs = require('fs'),
stdin = process.stdin,
stdout = process.stdout,
buffer = new Buffer(BUF_SIZE),
useShell = true;
2013-08-29 12:55:23 +02:00
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) {
2013-12-18 03:51:32 +01:00
var input = '', rsize, err;
2013-08-29 19:26:22 +02:00
if (display) { stdout.write(display, encoding); }
2013-08-29 12:55:23 +02:00
stdin.resume();
2013-12-17 18:18:39 +01:00
while (true) {
rsize = 0;
2013-12-18 03:51:32 +01:00
2013-12-17 18:18:39 +01:00
try {
rsize = fs.readSync(stdin.fd, buffer, 0, BUF_SIZE);
} catch (e) {
2013-12-18 03:51:32 +01:00
if (e.code === 'EOF') { break; } // pipe
if (useShell) {
// Try reading via shell
input = _readlineShell();
if (typeof input === 'string') { break; }
}
// Give up...
2013-12-18 03:51:32 +01:00
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');
2013-12-18 03:51:32 +01:00
err.errno = e.errno;
err.code = e.code;
2013-12-17 18:18:39 +01:00
}
2013-12-18 03:51:32 +01:00
if (display) { stdout.write('\n', encoding); } // Return from prompt line.
throw err || e;
2013-12-17 18:18:39 +01:00
}
2013-12-18 03:51:32 +01:00
2013-12-17 18:18:39 +01:00
if (rsize === 0) { break; }
2013-08-29 12:55:23 +02:00
input += buffer.toString(encoding, 0, rsize);
if (/[\r\n]$/.test(input)) { break; }
}
stdin.pause();
return input.trim();
}
// for dev
exports.useShellSet = function(use) { useShell = use; };
2013-08-29 19:26:22 +02:00
exports.setPrompt = function(newPrompt) {
if (typeof newPrompt === 'string') {
promptText = newPrompt;
}
};
exports.setEncoding = function(newEncoding) {
if (typeof newEncoding === 'string') {
encoding = newEncoding;
}
};
exports.prompt = function() {
return _readlineSync(promptText);
};
exports.question = function(query) {
return _readlineSync(typeof query === 'string' ? query : '');
};