Eva*_*oll 624 console node.js console.log
是否有一种方法可以在没有尾随换行符的情况下打印到控制台?该console对象的文档并没有说关于任何东西:
console.log()用换行符打印到stdout.此函数可以采用类似
printf()方式的多个参数.例:Run Code Online (Sandbox Code Playgroud)console.log('count: %d', count);如果在第一个字符串中找不到格式化元素,则
util.inspect在每个参数上使用.
ont*_*ia_ 966
你可以使用process.stdout.write():
process.stdout.write("hello: ");
Run Code Online (Sandbox Code Playgroud)
def*_*vol 358
此外,如果要覆盖同一行中的消息,例如在倒计时中,可以在字符串末尾添加"\ r".
process.stdout.write("Downloading " + data.length + " bytes\r");
Run Code Online (Sandbox Code Playgroud)
小智 18
在Windows控制台(也是Linux)中,您应该将'\ _ \'替换为等效代码\ 033 [0G:
process.stdout.write('ok\033[0G');
Run Code Online (Sandbox Code Playgroud)
这使用VT220终端转义序列将光标发送到第一列.
mra*_*xus 17
作为@rodowi上面关于能够覆盖一行的精彩内容的扩展/增强:
process.stdout.write("Downloading " + data.length + " bytes\r");
Run Code Online (Sandbox Code Playgroud)
如果我不希望终端光标位于第一个字符,正如我在代码中看到的那样,请考虑执行以下操作:
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)
Run Code Online (Sandbox Code Playgroud)
通过放置\r在下一个print语句的前面,光标在替换字符串覆盖前一个字符串之前被重置.
dou*_*uyw 13
util.print也可以使用.阅读:http://nodejs.org/api/util.html#util_util_print
util.print([...])#A同步输出功能.将阻塞进程,将每个参数转换为字符串,然后输出到stdout.在每个参数后不放置换行符.
一个例子:
// 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");
});
Run Code Online (Sandbox Code Playgroud)
似乎有许多答案表明process.stdout.write('\033[0G');.应该发出错误日志stdout(使用drain).对于任何想知道为什么process.stdout.write('\ 033 [0G'); 没有做任何事情,因为stdout是缓冲的,你需要等待false事件(参见NodeJS的Stdout flush?).如果write返回false,它将触发一个drain事件.
这些解决方案都不适合我,process.stdout.write('ok\033[0G')只是'\r'在 Mac OSX 10.9.2 上创建一个新行但不要覆盖。
编辑: 我不得不用它来替换当前行:
process.stdout.write('\033[0G');
process.stdout.write('newstuff');
Run Code Online (Sandbox Code Playgroud)
使用严格模式时出现以下错误:
节点错误:“严格模式下不允许使用八进制文字。”
以下解决方案有效(来源):
process.stdout.write("received: " + bytesReceived + "\x1B[0G");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
313647 次 |
| 最近记录: |