Node.js:在没有尾随换行符的情况下打印到控制台?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6157497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:13:56  来源:igfitidea点击:

Node.js: printing to console without a trailing newline?

node.jsconsoleconsole.log

提问by Evan Carroll

Is there a method for printing to the console without a trailing newline? The consoleobject documentationdoesn't say anything regarding that:

有没有一种没有尾随换行符的打印到控制台的方法?该console对象的文档并没有说关于任何东西:

console.log()

Prints to stdout with newline. This function can take multiple arguments in a printf()-like way. Example:

console.log('count: %d', count);

If formating elements are not found in the first string then util.inspectis used on each argument.

console.log()

使用换行符打印到标准输出。这个函数可以以类似printf()的方式接受多个参数。例子:

console.log('count: %d', count);

如果在第一个字符串中找不到格式化元素,则util.inspect在每个参数上使用它。

回答by onteria_

You can use process.stdout.write():

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

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

See the docs for details.

有关详细信息,请参阅文档

回答by defvol

Also, if you want to overwrite messages in the same line, for instance in a countdown, you could add '\r' at the end of the string.

此外,如果您想覆盖同一行中的消息,例如在倒计时中,您可以在字符串末尾添加 '\r'。

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

回答by Yan Te

In Windows console (Linux, too), you should replace '\r'with its equivalent code \033[0G:

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

process.stdout.write('ok3[0G');

This uses a VT220 terminal escape sequence to send the cursor to the first column.

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

回答by mraxus

As an expansion/enhancement to the brilliant addition made by @rodowi above regarding being able to overwrite a row:

作为对@rodowi 上面关于能够覆盖一行的精彩添加的扩展/增强:

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

Should you not want the terminal cursor to be located at the first character, as I saw in my code, the consider doing the following:

如果您不希望终端光标位于第一个字符处,如我在代码中所见,请考虑执行以下操作:

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)

By placing the \rin front of the next print statement the cursor is reset just before the replacing string overwrites the previous.

通过将 放在\r下一个打印语句的前面,光标会在替换字符串覆盖前一个之前重置。

回答by douyw

util.printcan be used also. Read: http://nodejs.org/api/util.html#util_util_print

util.print也可以使用。阅读:http: //nodejs.org/api/util.html#util_util_print

util.print([...])# A synchronous output function. Will block the process, cast each argument to a string then output to stdout. Does not place newlines after each argument.

util.print([...])# 一个同步输出函数。将阻塞进程,将每个参数转换为字符串,然后输出到标准输出。不在每个参数后放置换行符。

An example:

一个例子:

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

回答by Ahmed Masud

There seem to be many answers suggesting:

似乎有很多答案表明:

process.stdout.write

Error logs should be emitted on:

错误日志应在以下位置发出:

process.stderr

Instead use:

而是使用:

console.error

For anyone who is wonder why process.stdout.write('\033[0G');wasn't doing anything it's because stdoutis buffered and you need to wait for drainevent (more info).

对于任何想知道为什么process.stdout.write('\033[0G');不做任何事情的人来说,这是因为stdout已缓冲并且您​​需要等待drain事件(更多信息)。

If write returns falseit will fire a drainevent.

如果 write 返回false,它将触发一个drain事件。

回答by Tyguy7

None of these solutions work for me, process.stdout.write('ok\033[0G')and just using '\r'just create a new line but don't overwrite on Mac OSX 10.9.2.

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

EDIT:I had to use this to replace the current line:

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

process.stdout.write('3[0G');
process.stdout.write('newstuff');

回答by blablabla

I got the following error when using strict mode:

使用严格模式时出现以下错误:

Node error: "Octal literals are not allowed in strict mode."

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

The following solution works (source):

以下解决方案有效(来源):

process.stdout.write("received: " + bytesReceived + "\x1B[0G");