Node.js格式的控制台输出 [英] Node.js formatted console output

查看:148
本文介绍了Node.js格式的控制台输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的内置方法将格式化的数据输出到Node.js中的控制台?

Is there a simple built-in way to output formatted data to console in Node.js?

缩进,将字段向左或向右对齐,添加前导零?

Indent, align field to left or right, add leading zeros?

推荐答案

两个新(1)内置方法 String.Prototype.padStart String.Prototype.padEnd 在ES2017(ES8)中引入,可执行所需的填充功能。

Two new(1) built in methods String.Prototype.padStart and String.Prototype.padEnd were introduced in ES2017 (ES8) which perform the required padding functions.

(1)节点> = 8.2.1(如果使用--harmony标志运行,则为> = 7.5.0)

mdn页面中的示例:

Examples from the mdn page:

'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0");     // "00000abc"
'abc'.padStart(1);          // "abc" 

'abc'.padEnd(10);          // "abc       "
'abc'.padEnd(10, "foo");   // "abcfoofoof"
'abc'.padEnd(6, "123456"); // "abc123"
'abc'.padEnd(1);           // "abc"

要在控制台上缩进json,请尝试使用 JSON.stringify 。第三个参数提供所需的缩进。

For indenting a json onto the console try using JSON.stringify. The third parameter provides the indention required.

JSON.stringify({ a:1, b:2, c:3 }, null, 4);
// {
//    "a": 1,
//    "b": 2,
//    "c": 3
// }

这篇关于Node.js格式的控制台输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆