readline-sync/lib/readline-sync.js

227 lines
6.1 KiB
JavaScript
Raw Normal View History

2013-08-29 12:55:23 +02:00
/*
* readlineSync
* https://github.com/anseki/readline-sync
*
2015-01-26 17:11:25 +01:00
* Copyright (c) 2015 anseki
2013-08-29 12:55:23 +02:00
* Licensed under the MIT license.
*/
'use strict';
2014-07-13 06:55:17 +02:00
var
IS_WIN = process.platform === 'win32',
SHELL_PATH = IS_WIN ? 'cmd.exe' : '/bin/sh',
2015-03-02 14:44:36 +01:00
SHELL_COMMAND = __dirname + (IS_WIN ? '\\read.bat' : '/read.sh'),
2014-07-13 06:55:17 +02:00
ALGORITHM_CIPHER = 'aes-256-cbc',
ALGORITHM_HASH = 'sha256',
2013-08-29 19:26:22 +02:00
fs = require('fs'),
childProc = require('child_process'),
2013-08-29 19:26:22 +02:00
stdin = process.stdin,
stdout = process.stdout,
promptText = '> ',
encoding = 'utf8',
2015-02-22 14:23:46 +01:00
bufSize = 1024,
2015-03-02 14:44:36 +01:00
useShell = false, print, tempdir, salt = 0;
2014-07-12 00:37:25 +02:00
function _readlineSync(display, options) {
2015-02-22 12:57:07 +01:00
var input = '', buffer = new Buffer(bufSize),
rsize, err;
2015-03-02 14:44:36 +01:00
options = options || {};
2013-08-29 19:26:22 +02:00
if (display !== '') { // null and undefined were excluded.
2014-07-11 23:25:59 +02:00
if (typeof print === 'function') { print(display, encoding); }
stdout.write(display + '', encoding);
2014-07-11 23:25:59 +02:00
}
2013-08-29 12:55:23 +02:00
2015-03-02 14:44:36 +01:00
if (useShell || options.noEchoBack) { // Try reading via shell
2013-12-18 03:51:32 +01:00
2015-03-02 14:44:36 +01:00
input = _readlineShell(options);
2014-07-12 00:37:25 +02:00
if (typeof input !== 'string') {
if (display !== '') { stdout.write('\n', encoding); } // Return from prompt line.
2014-07-12 00:37:25 +02:00
throw new Error('Can\'t read via shell');
}
2014-07-12 00:37:25 +02:00
} else {
2014-07-12 00:37:25 +02:00
stdin.resume();
while (true) {
rsize = 0;
try {
2015-02-22 12:57:07 +01:00
rsize = fs.readSync(stdin.fd, buffer, 0, bufSize);
2014-07-12 00:37:25 +02:00
} catch (e) {
if (e.code === 'EOF') { break; } // pipe
2015-03-02 14:44:36 +01:00
// Try reading via shell
input = _readlineShell(options);
if (typeof input === 'string') { break; }
2014-07-12 00:37:25 +02:00
// 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');
err.errno = e.errno;
err.code = e.code;
}
if (display !== '') { stdout.write('\n', encoding); } // Return from prompt line.
2014-07-12 00:37:25 +02:00
throw err || e;
2013-12-17 18:18:39 +01:00
}
2014-07-12 00:37:25 +02:00
if (rsize === 0) { break; }
input += buffer.toString(encoding, 0, rsize);
if (/[\r\n]$/.test(input)) { break; }
2013-12-17 18:18:39 +01:00
}
2014-07-12 00:37:25 +02:00
stdin.pause();
2013-12-18 03:51:32 +01:00
2013-08-29 12:55:23 +02:00
}
2015-03-02 14:44:36 +01:00
return options.noTrim ? input.replace(/[\r\n]+$/, '') : input.trim();
}
2015-03-02 14:44:36 +01:00
function _readlineShell(options) {
var shellStdout, args = [],
execOptions = {
env: process.env,
stdio: [stdin], // ScriptPW needs piped stdin
encoding: encoding
2015-03-02 14:44:36 +01:00
};
2015-03-02 14:44:36 +01:00
if (options.noEchoBack) {
args.push('noechoback');
}
stdin.pause(); // re-start in child process
if (childProc.execFileSync) {
shellStdout = childProc.execFileSync(SHELL_PATH,
2015-03-02 14:44:36 +01:00
[SHELL_COMMAND].concat(args), execOptions);
shellStdout = shellStdout.replace(/^'|'$/g, '');
} else {
2015-03-02 14:44:36 +01:00
shellStdout = _execSyncByFile(args, execOptions);
}
return shellStdout;
}
// piping via files (node v0.10-)
2015-03-02 14:44:36 +01:00
function _execSyncByFile(args, execOptions) {
function getTempfile(name) {
var path = require('path'), filepath, suffix = '', fd;
tempdir = tempdir || require('os').tmpdir();
while (true) {
filepath = path.join(tempdir, name + suffix);
try {
fd = fs.openSync(filepath, 'wx');
} catch (e) {
if (e.code === 'EEXIST') {
suffix++;
continue;
} else {
throw e;
}
}
fs.closeSync(fd);
break;
}
return filepath;
}
2015-03-02 14:44:36 +01:00
var commandArgs, shellStdout,
pathStdout = getTempfile('readline-sync.stdout'),
pathStatus = getTempfile('readline-sync.status'),
2014-07-12 00:37:25 +02:00
pathDone = getTempfile('readline-sync.done'),
2014-07-13 06:55:17 +02:00
crypto = require('crypto'), shasum, decipher, password;
shasum = crypto.createHash(ALGORITHM_HASH);
shasum.update('' + process.pid + (salt++) + Math.random());
password = shasum.digest('hex');
decipher = crypto.createDecipher(ALGORITHM_CIPHER, password);
2015-03-02 14:44:36 +01:00
if (IS_WIN) {
// The quote (") is escaped by node before parsed by shell. Then use ENV{Q}.
process.env.Q = '"';
commandArgs = ['/V:ON', '/S', '/C',
'%Q%' + SHELL_COMMAND + '%Q% ' + args.join(' ') +
' |%Q%' + process.execPath + '%Q% %Q%' + __dirname + '\\encrypt.js%Q%' +
' %Q%' + ALGORITHM_CIPHER + '%Q% %Q%' + password + '%Q%' +
' >%Q%' + pathStdout + '%Q%' +
' & (echo !ERRORLEVEL!)>%Q%' + pathStatus + '%Q% & (echo 1)>%Q%' + pathDone + '%Q%'];
} else {
commandArgs = ['-c',
'DATA=`(' + SHELL_PATH + ' "' + SHELL_COMMAND + '" ' + args.join(' ') + ')`;' +
' RTN=$?; if [ $RTN -eq 0 ]; then (printf \'%s\' "$DATA"' +
' |"' + process.execPath + '" "' + __dirname + '/encrypt.js"' +
' "' + ALGORITHM_CIPHER + '" "' + password + '"' +
' >"' + pathStdout + '") fi;' +
' expr $RTN + $? >"' + pathStatus + '"; echo 1 >"' + pathDone + '"'];
}
childProc.spawn(SHELL_PATH, commandArgs, execOptions);
2014-07-13 08:32:02 +02:00
while (fs.readFileSync(pathDone, {encoding: encoding}).trim() !== '1') {}
if (fs.readFileSync(pathStatus, {encoding: encoding}).trim() === '0') {
2014-07-13 06:55:17 +02:00
shellStdout =
decipher.update(fs.readFileSync(pathStdout, {encoding: 'binary'}), 'hex', encoding) +
decipher.final(encoding);
shellStdout = shellStdout.replace(/^'|'$/g, '');
}
fs.unlinkSync(pathStdout);
fs.unlinkSync(pathStatus);
fs.unlinkSync(pathDone);
return shellStdout;
}
// for dev
2015-03-02 14:44:36 +01:00
exports._useShellSet = function(use) { useShell = use; };
2013-08-29 19:26:22 +02:00
2014-07-11 23:25:59 +02:00
exports.setPrint = function(fnc) { print = fnc; };
2013-08-29 19:26:22 +02:00
exports.setPrompt = function(newPrompt) {
/* jshint eqnull:true */
if (newPrompt != null) {
/* jshint eqnull:false */
promptText = newPrompt;
}
return promptText;
2013-08-29 19:26:22 +02:00
};
exports.setEncoding = function(newEncoding) {
if (typeof newEncoding === 'string') {
encoding = newEncoding;
}
return encoding;
2013-08-29 19:26:22 +02:00
};
2015-02-22 12:57:07 +01:00
exports.setBufferSize = function(newBufSize) {
if (typeof newBufSize === 'number') {
bufSize = newBufSize;
}
return bufSize;
};
2014-07-12 00:37:25 +02:00
exports.prompt = function(options) {
return _readlineSync(promptText, options);
2013-08-29 19:26:22 +02:00
};
2014-07-12 00:37:25 +02:00
exports.question = function(query, options) {
return _readlineSync(
/* jshint eqnull:true */
query != null ? query : '',
/* jshint eqnull:false */
options);
2013-08-29 19:26:22 +02:00
};
2015-03-01 15:46:52 +01:00
exports.keyIn = function(message) {
return _readlineSync(
/* jshint eqnull:true */
message != null ? message : '',
/* jshint eqnull:false */
{keyIn: true});
};