有没有一种方法可以在没有尾随换行符的情况下打印到控制台?
console
对象文档没有说明任何相关内容:
console.log()
使用换行符打印到标准输出。该函数可以以类似于
的方式接受多个参数。示例:printf()
console.log('count: %d', count);
如果在第一个字符串中找不到格式化元素,则在每个参数上使用
。util.inspect
此外,如果您想覆盖同一行中的消息(例如倒计时),您可以在字符串末尾添加
\r
。
process.stdout.write("Downloading " + data.length + " bytes\r");
作为对上面 @rodowi 所做的关于能够覆盖行的出色补充的扩展/增强:
process.stdout.write("Downloading " + data.length + " bytes\r");
如果您不希望终端光标位于第一个字符,正如我在代码中看到的那样,请考虑执行以下操作:
let dots = ''
process.stdout.write(`Loading `)
let tmrID = setInterval(() => {
dots += '.'
process.stdout.write(`\rLoading ${dots}`)
}, 1000)
setTimeout(() => {
clearInterval(tmrID)
console.log(`\rLoaded in [3500 ms]`)
}, 3500)
通过将
\r
放在下一个打印语句前面,光标将在替换字符串覆盖前一个字符串之前重置。
在 Windows 控制台(Linux 也是如此)中,您应该将
'\r'
替换为其等效代码 \033[0G
:
process.stdout.write('ok\033[0G');
这使用 VT220 终端转义序列将光标发送到第一列。
似乎有很多答案暗示:
process.stdout.write
错误日志应在以下位置发出:
process.stderr
改为使用:
console.error
对于任何想知道为什么
process.stdout.write('\033[0G');
没有做任何事情的人,这是因为 stdout
已缓冲,您需要等待 drain
事件(更多信息)。
如果 write 返回
false
它将触发 drain
事件。
util.print。阅读:http://nodejs.org/api/util.html#util_util_print
util.print([...])# 具有同步输出功能。将阻止进程,将每个参数转换为字符串,然后输出到标准输出。不在每个参数后放置换行符。
示例:
// get total length
var len = parseInt(response.headers['content-length'], 10);
var cur = 0;
// handle the response
response.on('data', function(chunk) {
cur += chunk.length;
util.print("Downloading " + (100.0 * cur / len).toFixed(2) + "% " + cur + " bytes\r");
});
这些解决方案都不适合我,
process.stdout.write('ok\033[0G')
并且仅使用'\r'
只是创建一个新行,但不要在Mac OSX 10.9.2上覆盖。
编辑:我必须用它来替换当前行:
process.stdout.write('\033[0G');
process.stdout.write('newstuff');
使用严格模式时出现以下错误:
节点错误:“严格模式下不允许使用八进制文字。”
以下解决方案有效(来源):
process.stdout.write("received: " + bytesReceived + "\x1B[0G");
如果您希望它在 Linux 和 Windows、严格模式和非严格模式下都能工作,并在每次打印时完全清除该行,您可以使用
const str = 'Hi there'
process.stdout.write(str.padEnd(50) + '\x1b[0G')
我的环境MacBook pro。我使用终端。对我来说没有任何作用。
感谢@shennan:
如果您的用例涉及尝试记录不断变化的数据,同时避免控制台膨胀,那么实现此目的的一种方法(在某些浏览器中)是在每次输出之前使用 console.clear() 。
console.clear();
console.log(msg);