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

前端 未结 5 1994
没有蜡笔的小新
没有蜡笔的小新 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: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)
    }
    

提交回复
热议问题