• Node.js Video Tutorials

NodeJS - console.log() 方法



Node.js 的 `console.log()` 方法用于将给定消息打印到标准输出流(stdout),即终端或其他日志记录机制,例如文件或网络连接。它接受任意数量的参数,并以空格分隔打印它们,并在末尾添加换行符。

假设我们需要在控制台上打印一些重要消息,Node.js 的 `console.log()` 方法很有用。如果我们想打印任何函数的输出等,`console.log()` 方法也可以完成这项任务。为了更好地理解,让我们了解一下 Node.js 的 `console.log()` 方法的语法和用法。

语法

以下是 Node.js `console.log()` 方法的语法:

console.log([data] [, …args]);

参数

此函数接受两个参数,如下所示。

  • data − 此参数指定将在控制台上显示的消息。

  • args − 这是一个可选参数,它保存将传递给 data 的替换值。

返回值

此方法不返回任何内容;相反,它将格式化的消息打印到控制台上的 stdout 中的新行。

示例

Node.js 的 `console.log()` 方法接受一个参数(`data`)。

在这个例子中,我们只使用 `data` 参数调用 `console.log()` 方法。

console.log("Welcome to Tutorialspoint");
console.log("Simply Easy Learning at your fingertips");

输出

正如我们在输出中看到的,`console.log()` 方法打印了我们作为 `data` 传递的消息。

Welcome to Tutorialspoint
Simply Easy Learning at your fingertips

示例

Node.js 的 `console.info()` 方法将接受一个可选参数(`args`)。

在这个例子中,我们使用两个参数 `data` 和 `args` 调用 `console.log()` 函数。我们传递 `string` 值作为替换值。

console.log("%s to %s", "Welcome", "Tutorialspoint");
console.log("%s Easy Learning at your %s", "Simply", "fingertips");

输出

正如我们在输出中看到的,我们传递到 `data` 中的消息与我们作为 `args` 传递的替换值一起打印到 `stdout` 的新行。

Welcome to Tutorialspoint
Simply Easy Learning at your fingertips

示例

在下面的例子中,我们做的与上面的例子类似,但是我们传递的是 `integer` 值作为 `args`,而不是 `string` 值。

console.log("Bahubali - %d, Bahubali - %d", 1,2);
console.log("Bahubali - %d collected %d crores around the globe", 2, 2000);

输出

正如我们在输出中看到的,替换值被传递到 `data` 中,并打印到 `stdout` 的新行。

Bahubali - 1, Bahubali - 2
Bahubali - 2 collected 2000 crores around the globe
nodejs_console_module.htm
广告