Nodejs中的cursorTo有什么用?

Pra*_*han 2 node.js

我读了一个nodejs的文件,遇到了一个方法cursorTo,我不明白它。请有人解释一下。

function refreshConsole () {
    if (Settings.properties.preventMessageFlicker) {
        readline.cursorTo(process.stdout, 0, 0);
    } else {
        process.stdout.write('\033c');
    }
}
Run Code Online (Sandbox Code Playgroud)

kga*_*har 5

如果你查看关于cursorTo的Nodejs文档,你会发现以下解释:

readline.cursorTo(流, x, y)

  • 流<可写>
  • x <数字>
  • y <数字>

readline.cursorTo() 方法将光标移动到给定 TTY 流中的指定位置

如果您想了解其实际工作原理,请创建一个test.js文件并将以下代码复制粘贴到其中。在控制台中执行使用node test.js

process.stdin.resume();
process.stdin.setEncoding('utf8');

console.log('This is interactive console for cursorTo explanation');

process.stdin.on('data', function (data) {
   // This is when only x value is given as input 
    for(i = 0; i< 10; i++){
        console.log('here x = '+ i + ' and y = 0' );
        require('readline').cursorTo(process.stdout, i);
    }
    // This is when  x  and y values are given as input
    // for(i = 0; i< 10; i++){
    //     console.log('here x = '+ i + ' and y = '+ i );
    //     require('readline').cursorTo(process.stdout, i, i);
    // }
});

process.on('SIGINT', function(){
    process.stdout.write('\n end \n');
    process.exit();
});
Run Code Online (Sandbox Code Playgroud)
  • 对于第一个 for 循环,您将得到如下响应:

    This is interactive console for cursorTo explanation
    hello
    here x = 0 and y = 0
    here x = 1 and y = 0
     here x = 2 and y = 0
      here x = 3 and y = 0
       here x = 4 and y = 0
        here x = 5 and y = 0
         here x = 6 and y = 0
          here x = 7 and y = 0
           here x = 8 and y = 0
            here x = 9 and y = 0
    
    Run Code Online (Sandbox Code Playgroud)
  • 这是因为对于每次执行require('readline').cursorTo(process.stdout, i),光标将指向x-ordinate我们给出的相应的下一行,并且y-ordinate为零。

  • 对于第二个 for 循环(在上面的代码中进行了注释),我们传递xy坐标。输出如下:

    here x = 1 and y = 1console for cursorTo explanation
    hhere x = 2 and y = 2
    hehere x = 3 and y = 3
       here x = 4 and y = 4
        here x = 5 and y = 5
         here x = 6 and y = 6
          here x = 7 and y = 7
           here x = 8 and y = 8
            here x = 9 and y = 9
    
    Run Code Online (Sandbox Code Playgroud)
  • 您可能会注意到第二个输出console for cursorTo explanation与文本重叠here。这是因为当给出坐标(x和)时,它会移回其开始位置,即“这是用于光标解释的交互式控制台”并打印位置,类似地,它移动并打印数据的每个坐标。y(0, 0)