readline-sync/lib/readline-sync.js

70 lines
1.6 KiB
JavaScript
Raw Normal View History

2013-08-29 12:55:23 +02:00
/*
* readlineSync
* https://github.com/anseki/readline-sync
*
* Copyright (c) 2013 anseki
* 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);
2013-08-29 12:55:23 +02:00
2013-08-29 19:26:22 +02:00
var _readlineSync = function(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 (e.code === 'EAGAIN') { // EAGAIN, resource temporarily unavailable
// util can't inherit Error.
2014-03-12 06:20:49 +01:00
err = new Error('The platform doesn\'t support interactively 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();
};
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 : '');
};