我读了一个nodejs的文件,遇到了一个方法cursorTo,我对此并不了解。请有人解释一下。
function refreshConsole () {
if (Settings.properties.preventMessageFlicker) {
readline.cursorTo(process.stdout, 0, 0);
} else {
process.stdout.write('\033c');
}
}
答案 0 :(得分:1)
如果您看到cursorTo的Nodejs文档,您会找到以下说明:
readline.cursorTo(stream,x,y)
- stream<可写>
- 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();
});
对于第一个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
这是因为每次执行require('readline').cursorTo(process.stdout, i)
时,光标都会指向下一行,我们正在给出x-ordinate
,y-ordinate
为零。
对于第二个for循环(在上面的代码中已注释),我们传递了x
和y
个纵坐标。输出如下:
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
您可能会注意到第二个输出console for cursorTo explanation
与文本here
重叠。这是因为当给出两个纵坐标(x
和y
)时,对于(0, 0)
,它会移回到它开始接近&#34; 这是光标的交互式控制台解释&#34;并打印位置,类似地,对于每个纵坐标,它移动并打印数据。