从node.js教程中,我看到了这两个process.stdout函数:
process.stdout.clearLine(); process.stdout.cursorTo(0);
但我使用的是更新的node.js版本(4.2.4),并且这些功能不存在.我得到的process.stdout.clearLine is not a function
和process.stdout.cursorTo is not a function
.
node.js版本4.2.4上clearLine和cursorTo的等价物是什么?
编辑:
这些都不起作用:
process.readline.clearLine(); process.readline.cursorTo(0); function writeWaitingPercent(p) { process.readline.clearLine(); process.readline.cursorTo(0); process.stdout.write(`waiting ... ${p}%`); }
我明白了 Cannot read property 'clearLine' of undefined
这是解决方案:
首先,要求readline:
var readline = require('readline');
然后,像这样使用cursorTo:
function writeWaitingPercent(p) { //readline.clearLine(process.stdout); readline.cursorTo(process.stdout, 0); process.stdout.write(`waiting ... ${p}%`); }
我已经评论过clearLine,因为它在我的情况下是无用的(cursorTo将光标移回到开头)
该的Readline模块是Node.js的一部分现在提供readline.cursorTo(stream, x, y)
,readline.moveCursor(stream, dx, dy)
和readline.clearLine(stream, dir)
方法.
使用TypeScript,您的代码应如下所示:
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) }
以前的代码将转换为以下Javascript(ES6)代码:
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); }
作为替代方案,您可以将以下代码用于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) }