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 - 这是一个可选参数,它包含将传递给数据的替换值。
返回值
此方法不返回任何内容;相反,它会在控制台上以新行的形式将格式化的消息打印到 stdout。
例Node.js console.log() 方法的 node.js 接受一个参数 (data)。
在此示例中,我们仅使用数据参数调用 console.log() 方法。
console.log("Welcome to qikepu");
console.log("Simply Easy Learning at your fingertips");
输出
正如我们在输出中看到的,console.log() 方法打印我们作为数据传递的消息。
Simply Easy Learning at your fingertips
例
node.js 的 console.info() 方法将接受可选参数 (args)。
在此示例中,我们使用两个参数 data 和 args 调用 console.log() 函数。我们将字符串值作为替换值传递。
console.log("%s to %s", "Welcome", "qikepu");
console.log("%s Easy Learning at your %s", "Simply", "fingertips");
输出
正如我们在输出中看到的,我们传递给 data 的消息与我们作为 args 传递的替换值一起以换行符的形式打印到 stdout。
Simply Easy Learning at your fingertips
例
在下面的示例中,我们正在执行类似于上述示例的操作,但是我们不是将字符串值作为参数传递,而是传递整数值。
console.log("Bahubali - %d, Bahubali - %d", 1,2);
console.log("Bahubali - %d collected %d crores around the globe", 2, 2000);
输出
正如我们在输出中看到的,替换值被传递到数据中,并以换行符的形式打印到 stdout。
Bahubali - 2 collected 2000 crores around the globe