I'm having problems with node.js' readline. Shown below is the console output: the stuff in bold is what I am typing, the rest is what is being logged by the server.
> Teslog message > Testinlog message > log message log message Tlog message estinglog message > 123
Put simply, my code looks like this
setInterval(function() { console.log("log message") }, 1000);
var cli = require('readline').createInterface(process.stdin, process.stdout);
cli.setPrompt("> ", 2);
cli.on('line', function(line) {
cli.prompt();
});
cli.prompt();
How can I get the prompt to shift down to give the new output room, without completely trashing whatever I am typing?
readline.createInterface(options) Accepts an "options" Object that takes the following values: input - the readable stream to listen to (Required). output - the writable stream to write readline data to (Optional). completer - an optional function that is used for Tab autocompletion.
The Readline module provides a way of reading a datastream, one line at a time.
log() The console. log() method outputs a message to the web console.
const readline = require('readline'); Since readline module works only with Readable streams, so we need to first create a readable stream using the fs module. // but from a readable stream only. The line-reader module provides eachLine() method which reads the file line by line.
This appears to somewhat solve the problem - the prompt at least gets redrawn after the console is logged to.
var log = console.log;
console.log = function() {
// cli.pause();
cli.output.write('\x1b[2K\r');
log.apply(console, Array.prototype.slice.call(arguments));
// cli.resume();
cli._refreshLine();
}
However, the interrupted prompt does not get cleared.
EDIT: adding cli.output.write('\x1b[2K\r');
made it work
EDIT 2: More complete solution, making other things like util.log
work as well:
function fixStdoutFor(cli) {
var oldStdout = process.stdout;
var newStdout = Object.create(oldStdout);
newStdout.write = function() {
cli.output.write('\x1b[2K\r');
var result = oldStdout.write.apply(
this,
Array.prototype.slice.call(arguments)
);
cli._refreshLine();
return result;
}
process.__defineGetter__('stdout', function() { return newStdout; });
}
#EDIT 3: Looks like cli.pause()
and cli.resume()
before and after the call are redundant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With