"process.stdout. "在node.js中写入“和”console.log“?

EDIT:使用console.log作为变量显示了许多不可读的字符,而使用process.stdout.write显示了一个对象。

为什么呢?


当前回答

Console.log()每次调用它都会添加大量内容和新行

Process.stdout.write()只是纯文本,没有格式

至少我是这么被教导的

其他回答

对于那些喜欢Deno的人,我可以通过使用下面的ANSI转义序列和Deno版本的process.stdout.write来实现这一点。

ESC[2K  clears entire line
ESC[#G  moves cursor to column #

Code

/*
    Console.log() to the same line
    Supported in Deno 1.8.1
*/

const myTextEncoder : TextEncoder = new TextEncoder();

let counter : number = 0;

while(counter < 100000) {

  // ESC[2K clears entire line
  await Deno.stdout.write(myTextEncoder.encode(`\x1b[2K`));
  // ESC[#G moves cursor to column #
  await Deno.stdout.write(myTextEncoder.encode(`\x1b[0G`));
  // OUTPUT incremented counter
  await Deno.stdout.write(myTextEncoder.encode(`COUNTER: ${counter++}`));

}

Console.log()使用格式化输出调用process.stdout.write。具体实现请参见console.js中的format()。

目前(v0.10.ish):

Console.prototype.log = function() {
  this._stdout.write(util.format.apply(this, arguments) + '\n');
};

这个上下文中另一个重要的区别是process.stdout.clearLine()和process.stdout.cursorTo(0)。

如果您想在一行中显示下载或处理的百分比,这将非常有用。如果你使用clearLine(), cursorTo()与console.log(),它不会工作,因为它也附加\n到文本。试试这个例子:

var totalTime = 5000;
var waitInterval = totalTime / 10;
var currentInterval = 0;

function showPercentage(percentage){
    process.stdout.clearLine()
    process.stdout.cursorTo(0)
    console.log(`Processing ${percentage}%...` ) // Replace this line with process.stdout.write(`Processing ${percentage}%...`)
}

var interval = setInterval(function(){
    currentInterval += waitInterval
    showPercentage((currentInterval / totalTime) * 100)
}, waitInterval)

setTimeout(function(){
    clearInterval(interval)
}, totalTime + 100)

查看Node文档,显然console.log只是process.stdout.write,在结尾加一个换行符:

console.log = function (d) {
  process.stdout.write(d + '\n');
};

来源:http://nodejs.org/docs/v0.3.1/api/process.html process.stdout

Console.log()每次调用它都会添加大量内容和新行

Process.stdout.write()只是纯文本,没有格式

至少我是这么被教导的