node.js stdout clearline() and cursorTo() functions

前端 未结 5 1968
没有蜡笔的小新
没有蜡笔的小新 2020-12-25 12:11

From a node.js tutorial, I see those two process.stdout functions :

process.stdout.clearLine();
process.stdout.cursorTo(0);

But I\'m using

相关标签:
5条回答
  • 2020-12-25 12:29

    process.readline.cursorTo and process.readline.clearLine

    Node v4.2.4 Documentation

    0 讨论(0)
  • 2020-12-25 12:30

    The Readline module that is part of Node.js now provides readline.cursorTo(stream, x, y), readline.moveCursor(stream, dx, dy) and readline.clearLine(stream, dir) methods.


    With TypeScript, your code should look like this:

    import * as readline from 'readline'
    // import readline = require('readline') also works
    
    /* ... */
    
    function writeWaitingPercent(p: number) {
        readline.clearLine(process.stdout, 0)
        readline.cursorTo(process.stdout, 0, null)
        let text = `waiting ... ${p}%`
        process.stdout.write(text)
    }
    

    The previous code will transpile into the following Javascript (ES6) code:

    const readline = require('readline');
    
    /* ... */
    
    function writeWaitingPercent(p) {
        readline.clearLine(process.stdout, 0);
        readline.cursorTo(process.stdout, 0, null);
        let text = `waiting ... ${p}%`;
        process.stdout.write(text);
    }
    

    As an alternative, you can use the following code for Javascript (ES6):

    const readline = require('readline');
    
    /* ... */
    
    function waitingPercent(p) {
        readline.clearLine(process.stdout, 0)
        readline.cursorTo(process.stdout, 0)
        let text = `waiting ... ${p}%`
        process.stdout.write(text)
    }
    
    0 讨论(0)
  • 2020-12-25 12:32

    if you see stdout exceptions like TypeError: process.stdout.clearLine is not a function in Debug Console window of Visual Studio Code (or Webstorm), run the app as external terminal application instead of internal console. The reason is that Debug Console window is not TTY (process.stdout.isTTY is false). Therefore update your launch configuration in launch.json with "console": "externalTerminal" option.

    0 讨论(0)
  • 2020-12-25 12:48

    This is the solution :

    First, require readline :

    var readline = require('readline');
    

    Then, use cursorTo like this :

    function writeWaitingPercent(p) {
        //readline.clearLine(process.stdout);
        readline.cursorTo(process.stdout, 0);
        process.stdout.write(`waiting ... ${p}%`);
    }
    

    I've commented clearLine, since it's useless in my case (cursorTo move back the cursor to the start)

    0 讨论(0)
  • 2020-12-25 12:49

    For my part, I had the clearline is not a function error in a package that use process.stdout.clearline().

    I had to start my windows console as administrator to make it works.

    0 讨论(0)
提交回复
热议问题