Better prompt interface when a new line is added when input is active
- Readline always available ;
- Support for debug module with
myRL._debugModuleSupport(require('debug'))
; - Commands history ;
- Autocompletition ;
- No split between input & output ;
- Password mode to hide input (try 'pwd' command), more effect here ;
- You can eval command or javascript function like browser.
Support Windows/Linux/(Mac?) and node >=10 (for oldest version see below)
npm install serverline
process.stdout.write('\x1Bc')
const myRL = require('serverline')
myRL.init()
myRL.setCompletion(['help', 'command1', 'command2', 'login', 'check', 'ping'])
myRL.setPrompt('> ')
myRL.on('line', function(line) {
console.log('cmd:', line)
switch (line) {
case 'help':
console.log('help: To get this message.')
break
case 'pwd':
console.log('toggle muted', !myRL.isMuted())
myRL.setMuted(!myRL.isMuted(), '> [hidden]')
return true
case 'secret':
return myRL.secret('secret:', function() {
console.log(';)')
})
}
if (myRL.isMuted())
myRL.setMuted(false)
})
myRL.on('SIGINT', function(rl) {
rl.question('Confirm exit: ', (answer) => answer.match(/^y(es)?$/i) ? process.exit(0) : rl.output.write('\x1B[1K> '))
})
function displayFakeLog() {
let i = 0
setInterval(function() {
const num = () => Math.floor(Math.random() * 255) + 1
i++
console.log(i + ' ' + num() + '.' + num() + '.' + num() + ' user connected.')
}, 700)
}
displayFakeLog()
myRL.on('line', function(line) {
try {
console.log(eval(line))
} catch (e) {
console.error(e)
}
})
See node > 9.5 and oldest version
process.env.DEBUG = '*'
const debug = require('debug')('server::info')
const myRL = require('serverline')
myRL.init()
myRL._debugModuleSupport(require('debug'))
myRL.setPrompt('> ')
function displayFakeLog() {
let i = 0
setInterval(function() {
const num = () => Math.floor(Math.random() * 255) + 1
i++
debug(i + ' ' + num() + '.' + num() + '.' + num() + ' user connected.')
}, 700)
}
displayFakeLog()
options
(Object
|String
if is String the value will be set tooptions.prompt
):prompt
(String
, default:'> '
): Set the prompt that will be written to output.ignoreErrors
(Boolean
, default:true
): Ignore errors when writing to the underlying streams. By defaultConsole
instance is on silent mode, it will catch error without print anything (in dev mode, set tofalse
).colorMode
(Boolean
|String
, default:'auto'
): Set color support for theConsole
instance, enable color withtrue
Read more.inspectOptions
Object
: Specifies options that are passed along to util.inspect().forceTerminalContext
(Boolean
, default:false
): Force node to use stdin like a real terminal. This setting is usefull if you redirect the output (withnpm start > file.txt
,npm start | tee file.txt
, child_process, ...).
Start serverline's readline.
const myRL = require('serverline')
myRL.init()
query
String
: A statement or query to write to output, prepended to the prompt.callback
Function
: A callback function that is invoked with the user's input in response to the query.
Display the query by writing it to the output, waits for user input to be provided on input and press ENTER
, then invokes the callback function passing the provided input as the first argument.
The input will be hidden with [-=]
and [=-]
.
myRL.init()
myRL.secret('secret:', function() {
console.log(';)')
})
// output :
// secret:[-=]
query
String
: A statement or query to write to output, prepended to the prompt.callback
Function
: A callback function that is invoked with the user's input in response to the query.
Display the query by writing it to the output, waits for user input to be provided on input and press ENTER
, then invokes the callback function passing the provided input as the first argument.
myRL.init()
myRL.question('What is your favorite food? ', (answer) => {
console.log(`Oh, so your favorite food is ${answer}.`)
})
- Returns
String
: Gets the current prompt that is written to output
strPrompt
String
: Sets the prompt that will be written to output
- Returns
Boolean
: True if the input is hidden
enabled
Boolean
: Enable/DisablestrPrompt
String
: Sets the prompt that will be written to output
Enable hidden input:
console.log('toggle muted', !myRL.isMuted())
myRL.setMuted(true, '> [hidden]')
// output :
// > [hidden][-=]
Disable hidden input:
disable : myRL.setMuted(false)
obj
Array[String]
: Strings/commands displayed in autocompletion.
If you want use your own completion function use (see below an example): myRL.on('completer', completerFunction)
.
Example:
myRL.init()
myRL.setCompletion(['help', 'command1', 'command2', 'login', 'check', 'ping'])
- Returns
Array[String]
: List of commands
Get History.
- Returns
Array[String]
: List of commands
Rewrite history.
- Returns: An Object with
stdout
andstderr
used by serverline.
Use Serverline.getCollection().stdout.write('msg\n')
can be usefull if you don't want to use console.log('msg')
. Serverline.getCollection().stdout
is different of process.stdout
. Prefere to use Serverline.getCollection().stdout.write('msg\n')
instead process.stdout.write('msg\n')
because if you use process.stdout.write
, you will get some prompt displays bugs.
- Returns: The readline instance
We recommand to use Serverline.<function>()
function instead Serverline.getRL().<function>()
.
Close the readline.Interface
instance and relinquishe control over the input
and output
streams. When called, the 'close'
event will be emitted.
Calling rl.close()
does not immediately stop other events (including 'line'
) from being emitted.
Pause the input
stream, allowing it to be resumed later if necessary.
Calling .pause()
does not immediately pause other events (including 'line'
) from being emitted.
Resume the input stream if it has been paused.
eventName
(String
|Symbol
): The name of the eventlistener
Function
: The callback function
Adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times. Read more
Serverline/Rewrited events :
- Event: 'line'
- Event: 'SIGINT'
- Event: 'completer'
Navtive Readline events :
- Event: 'close'
- Event: 'pause'
- Event: 'resume'
- Event: 'SIGCONT'
- Event: 'SIGTSTP'
The 'line'
event is emitted whenever the input stream receives an end-of-line input (\n
, \r
, or \r\n
). This usually occurs when the user presses the <Enter>
, or <Return>
keys.
The listener function is called with a string containing the single line of received input.
myRL.init({
prompt: '> '
})
myRL.on('line', function(line) {
console.log('cmd:', line)
if (line == 'help') {
console.log('help: To get this message.')
}
})
The 'SIGINT'
event is emitted whenever the input
stream receives a <ctrl>-C
input, known typically as SIGINT
. If there are no 'SIGINT'
event listeners registered when the input stream receives a SIGINT
, the 'pause'
event will be emitted.
The listener function is invoked without passing any arguments.
myRL.on('SIGINT', function(rl) {
rl.question('Confirm exit: ', (answer) => answer.match(/^y(es)?$/i) ? process.exit(0) : rl.output.write('\x1B[1K> '))
})
- arg (Object = { line, hits})
- line
String
: current line - hits
Array[String]
: all completion will be displayed
- line
You can make a better completer with dynamic values :
process.stdout.write('\x1Bc')
const myRL = require('serverline')
myRL.init({
prompt: '> '
})
myRL.setCompletion(['.backup', '.forceupdate', '.open', '.compare', '.rename', '.sandbox'])
myRL.on('completer', function(arg) {
if (arg.hits.length == 1) {
arg.line = arg.hits[0]
}
arg.hits = completerId('.backup ', arg.line, arg.hits)
arg.hits = completerId('.forceupdate ', arg.line, arg.hits)
arg.hits = completerId('.open ', arg.line, arg.hits)
arg.hits = completerId('.compare ', arg.line, arg.hits)
arg.hits = completerId('.rename ', arg.line, arg.hits)
arg.hits = completerId('.sandbox ', arg.line, arg.hits)
})
const user_id = [1, 2, 3, 4]
function completerId(cmd, line, hits, verify) {
var verify = (verify) ? verify : function(id, index) {
return true
}
var t = [cmd]
if (line.indexOf(cmd) == 0) {
user_id.forEach(function(id, index) {
if (!verify(id, index)) {
return
}
t.push(cmd + id)
})
hits = t.filter(function(c) {
return c.indexOf(line) == 0
})
if (hits.length == 0) {
hits = t
}
}
return hits
}
Output:
> .back
Suggestion:
.backup, .forceupdate, .open, .compare, .rename, .sandbox
> .backup
Suggestion:
.backup, .backup 1, .backup 2, .backup 3, .backup 4
myRL.on('close', function(line) {
console.log('bye')
})
myRL.on('pause', function(line) {
console.log('pause')
})
myRL.on('resume', function(line) {
console.log('resume')
})
The 'SIGCONT'
event is not supported on Windows.
The 'SIGTSTP'
event is not supported on Windows.