Javascript node.js 中“process.stdout.write”和“console.log”的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4976466/
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-08-23 15:02:31  来源:igfitidea点击:

Difference between "process.stdout.write" and "console.log" in node.js?

javascriptnode.js

提问by ajsie

What is the difference between "process.stdout.write" and "console.log" in node.js?

node.js 中的“process.stdout.write”和“console.log”有什么区别?

EDIT: Using console.log for a variable showed a lot of unreadable characters while using process.stdout.write showed an object.

编辑:在使用 process.stdout.write 显示对象时,将 console.log 用于变量显示了很多不可读的字符。

Why is that?

这是为什么?

采纳答案by TK-421

console.log()calls process.stdout.writewith formatted output. See format()in console.js for the implementation.

console.log()process.stdout.write带有格式化输出的调用。有关format()实现,请参见console.js。

Currently (v0.10.ish):

目前(v0.10.ish):

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

回答by Mauvis Ledford

Looking at the Node docs apparently console.log is just process.stdout.write with a line-break at the end:

查看 Node 文档,显然 console.log 只是 process.stdout.write ,最后有一个换行符:

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

Source: http://nodejs.org/docs/v0.3.1/api/process.html#process.stdout

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

回答by Gepser

I know this is a very old question but I didn't see anybody talking about the main difference between process.stdout.writeand console.logand I just want to mention it.

我知道这是一个非常古老的问题,但我没有看到任何人谈论的主要区别process.stdout.writeconsole.log我只是想提一提它。

As Mauvis Lefordand TK-421pointed out, the console.logadds a line-breakcharacter at the end of the line (\n) but that's not all what it does.

正如Mauvis LefordTK-421指出的那样,它console.logline-break在行尾 ( \n)添加一个字符,但这并不是它所做的全部。

The code has not changed since at least 0.10.Xversion and now we have a a 5.Xversion.

代码至少从0.10.X版本开始没有改变,现在我们有了一个5.X版本。

Hereis the code:

是代码:

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

As you can see, there is a part that says .apply(this, arguments)and that makes a big difference on functionality. It is easier to explain that with examples:

正如您所看到的,有一个部分说.apply(this, arguments),这对功能产生了很大的影响。用例子更容易解释:

process.stdout.writehas a very basic functionality, you can just write something in there, like this:

process.stdout.write有一个非常基本的功能,你可以在那里写一些东西,像这样:

process.stdout.write("Hello World\n"); 

If you don't put the break line at the end you will get a weird character after your string, something like this:

如果您不将换行符放在最后,您的字符串后面会出现一个奇怪的字符,如下所示:

process.stdout.write("Hello World"); //Hello World% 

(I think that means something like "the end of the program", so you will see it only if you process.stdout.writewas used at the end of your file and you didn't add the break line)

(我认为这意味着类似于“程序的结尾”,因此只有process.stdout.write在文件末尾使用并且未添加中断行时,您才会看到它)

On the other hand, console.logcan do more.

另一方面,console.log可以做得更多。

  1. You can use it in the same way

    console.log("Hello World"); //You don't need the break line here because it was already formatedand also that weird character did disappear

  2. You can write more than one string

    console.log("Hello", "World");

  3. You can make associations

    console.log("Hello %s", "World") //Useful when "World" is inside a variable

  1. 你可以用同样的方式使用它

    console.log("Hello World"); //You don't need the break line here because it was already formated而且那个奇怪的角色确实消失了

  2. 你可以写多个字符串

    console.log("Hello", "World");

  3. 你可以建立关联

    console.log("Hello %s", "World") //Useful when "World" is inside a variable

An that's it, that added functionality is given thanks to the util.format.applypart (I could talk a lot about what exactly this does but you get my point, you can read more here).

就是这样,由于该util.format.apply部分提供了附加功能(我可以谈论很多关于这到底是做什么的,但您明白我的意思,您可以在此处阅读更多内容)。

I hope somebody find this information useful.

我希望有人觉得这些信息有用。

回答by thelostspore

One big difference that hasn't been mentioned is that process.stdoutonly takes strings as arguments (can also be piped streams), while console.logtakes any Javascript data type.

一个尚未提及的重大区别是process.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)

回答by saikirann

Another important difference in this context would with process.stdout.clearLine()and process.stdout.cursorTo(0).

这种情况下的另一个重要区别是process.stdout.clearLine()process.stdout.cursorTo(0)

This would be useful if you want to show percentage of download or processing in the only one line. If you use clearLine(), cursorTo() with console.log()it doesn't work because it also append \n to the text. Just try out this example:

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

var waitInterval = 500;
var totalTime = 5000;
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);

回答by Nova

I've just noticed something while researching this after getting help with https.request for post method. Thought I share some input to help understand.

在获得 https.request for post 方法的帮助后,我刚刚在研究这个问题时注意到了一些事情。我想我分享一些输入来帮助理解。

process.stdout.writedoesn't add a new line while console.logdoes, like others had mentioned. But there's also this which is easier to explain with examples.

process.stdout.write不会console.log像其他人提到的那样添加新行。但也有这个更容易用例子来解释。

var req = https.request(options, (res) => {
    res.on('data', (d) => {
        process.stdout.write(d);
        console.log(d)
    });
});

process.stdout.write(d);will print the data properly without a new line. However console.log(d)will print a new line but the data won't show correctly, giving this <Buffer 12 34 56...for example.

process.stdout.write(d);将正确打印数据而无需换行。但是console.log(d)会打印一个新行,但数据不会正确显示,<Buffer 12 34 56...例如。

To make console.log(d)show the information correctly, I would have to do this.

为了console.log(d)正确显示信息,我必须这样做。

var req = https.request(options, (res) => {
    var dataQueue = "";    
    res.on("data", function (d) {
        dataQueue += d;
    });
    res.on("end", function () {
        console.log(dataQueue);
    });
});

So basically:

所以基本上:

  • process.stdout.writecontinuously prints the information as the data being retrieved and doesn't add a new line.

  • console.logprints the information what was obtained at the point of retrieval and adds a new line.

  • process.stdout.write连续打印信息作为正在检索的数据并且不添加新行。

  • console.log打印在检索点获得的信息并添加新行。

That's the best way I can explain it.

这是我能解释的最好方法。

回答by Rishu Anand

The Simple Difference is: console.log()methods automatically append new line character. It means if we are looping through and printing the result, each result get printed in new line.

简单的区别是: console.log()方法自动附加换行符。这意味着如果我们循环并打印结果,每个结果都会打印在新行中。

process.stdout.write()methods don't append new line character. useful for printing patterns.

process.stdout.write()方法不附加换行符。用于打印图案。