Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readline with console.log in the background

Tags:

node.js

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?

like image 424
Eric Avatar asked May 15 '12 18:05

Eric


People also ask

What is readline createInterface?

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.

What does readline () do in Javascript?

The Readline module provides a way of reading a datastream, one line at a time.

What is the output console log (' one ')?

log() The console. log() method outputs a message to the web console.

How do I read a file line by line in node?

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.


1 Answers

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.

like image 52
Eric Avatar answered Oct 02 '22 02:10

Eric