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

EDIT:使用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++}`));

}

其他回答

这个上下文中另一个重要的区别是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)

一个没有被提及的巨大区别是这个过程。stdout只接受字符串作为参数(也可以是管道流),而console.log接受任何Javascript数据类型。

e.g:

// ok
console.log(null)
console.log(undefined)
console.log('hi')
console.log(1)
console.log([1])
console.log({one:1})
console.log(true)
console.log(Symbol('mysymbol'))

// any other data type passed as param will throw a TypeError
process.stdout.write('1')

// can also pipe a readable stream (assuming `file.txt` exists)
const fs = require('fs')
fs.createReadStream('file.txt').pipe(process.stdout)

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++}`));

}

实现process.sdout。Write, process. sout . Write是一个直接输出到控制台的缓冲区/流。

根据我的puglin serverline: console = new console (consoleOptions),您可以用自己的readline系统重写console类。

你可以看到console.log的源代码:

第十四节。X - lib/internal/console/constructor.js; 对于旧版本:v10.0.0 - lib/console.js。


更多信息:

readline。创建你的自定义行为或使用控制台输入。