Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js formatted console output

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?

like image 824
exebook Avatar asked Nov 07 '13 13:11

exebook


People also ask

How do I print a node js console?

log() function from console class of Node. js is used to display the messages on the console. It prints to stdout with newline. Parameter: This function contains multiple parameters which are to be printed.

How do I print from console?

We can print messages to the console conditionally with console. assert() . If the first argument is false, then the message will be logged. If we were to change isItWorking to true , then the message will not be logged.

What will the output of console log Hello world using node js?

console. log("Hello", "World"); Output: This will print Hello World in the console.


1 Answers

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) node >= 8.2.1 (or >= 7.5.0 if run with the --harmony flag)

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" 

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 // } 
like image 76
TheChetan Avatar answered Nov 08 '22 20:11

TheChetan