有没有一种在没有尾随换行符的情况下打印到控制台的方法?console
对象文档没有说明任何相关内容:
console.log()
使用换行符打印到标准输出。
printf()
这个函数可以以类似的方式接受多个参数。例子:console.log('count: %d', count);
如果在第一个字符串中未找到格式化元素,则
util.inspect
在每个参数上使用。
有没有一种在没有尾随换行符的情况下打印到控制台的方法?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')