首页 文章

Node.js:打印到控制台没有尾随换行符?

提问于
浏览
541

是否有一种方法可以在没有尾随换行符的情况下打印到控制台? console 对象documentation没有说明任何相关内容:

console.log()使用换行符打印到stdout . 这个函数可以在printf()中使用多个参数 . 示例:console.log('count:%d',count);
如果在第一个字符串中找不到格式化元素,则在每个参数上使用util.inspect .

8 回答

  • 7

    你可以使用 process.stdout.write()

    process.stdout.write("hello: ");
    

    docs for details .

  • 3

    此外,如果要覆盖同一行中的消息,例如在倒计时中,可以在字符串末尾添加“\ r” .

    process.stdout.write("Downloading " + data.length + " bytes\r");
    
  • 4

    在Windows控制台(也是Linux)中,您应该将'\r'替换为其等效代码 \033[0G

    process.stdout.write('ok\033[0G');
    

    这使用VT220终端转义序列将光标发送到第一列 .

  • 15

    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");
    });
    
  • 6

    似乎有许多答案表明 process.stdout.write . 应该在 process.stderr 上发出错误日志(使用 console.error ) . 对于任何想知道为什么process.stdout.write('\033[0G');因为stdout是缓冲的,你需要等待 drain 事件(见Stdout flush for NodeJS?) . 如果write返回false,它将触发 drain 事件 .

  • 13

    作为@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 放在下一个print语句的前面,光标会在替换字符串覆盖前一个字符串之前重置 .

  • 832

    使用严格模式时出错 .

    节点错误:“严格模式下不允许使用八进制文字 . ”

    我在这里找到了答案:https://github.com/SBoudrias/Inquirer.js/issues/111

    process.stdout.write(“received:”bytesReceived“\ x1B [0G”);

  • 320

    这些解决方案都不适合我 . process.stdout.write('ok \ 033 [0G')并且只使用'\ r'只创建一个新行,不要覆盖,Mac OSX 10.9.2

    编辑:我不得不使用它来替换当前行

    process.stdout.write( '\ 033 [0G'); process.stdout.write( 'Newstuff文件');

相关问题