78

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?

4
  • 1
    I don't know about any of those, but similar one is colors and it can format the strings outputted e.g. "Green colour".green
    – Matej
    Nov 7, 2013 at 13:53
  • I'm assuming you're asking to do something like console.setup({ color: 'green', prepend: '0000' }), but already built in? You could make your own logging method or override the stdout.write method (although people suggest not overriding native functions).
    – matth
    Nov 7, 2013 at 14:35
  • 1
    I was thinking about printf() with various handy format modifiers to the output string.
    – exebook
    Nov 7, 2013 at 17:13
  • The answers below are good. In addition though, if you also want to add automatic colors to your standard Node.js output, check out manakin.
    – vitaly-t
    Dec 2, 2016 at 12:24

8 Answers 8

75
+25

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
// }
3
  • 3
    May be worthwhile to note that this is supported only in node >= 8.2.1 (or >= 7.5.0 if run with the --harmony flag) since it is rather recent yet.
    – Semicolon
    Sep 9, 2017 at 5:37
  • This is working for me on v8.1.2 even without the flag. Jan 4, 2018 at 20:50
  • Don't forget to use .toString() if you're not seeing this work.
    – mdhansen
    Feb 5, 2020 at 22:49
35

If the data is tabular, then the simplest way would be to do it with console.table

https://nodejs.org/dist/latest-v10.x/docs/api/console.html#console_console_table_tabulardata_properties

This is the code.

console.table(
  COMMANDS.map(command => {
    return {
      "Long Option": command.long_option,
      "Short Option": command.short_option,
      Description: command.description
    };
  })
);

You don't need external libraries for it. Here is sample output. You only need to pass an array object. enter image description here

Not only in Nodejs, but it also works in chrome.

https://developer.mozilla.org/en-US/docs/Web/API/Console/table

enter image description here

2
  • 17
    Any way to left indent the contents of column? It defaults to center alignment. Aug 29, 2020 at 0:12
  • 3
    Is there way to align text to left? Dec 17, 2020 at 5:39
28

There's nothing built into NodeJS to do this. The "closest" you'd come is util.format, which still doesn't do much unfortunately (reference).

You'll need to look into other modules to provide a richer formatting experience. For example: sprintf.

Sprintf-js allows both positional (0, 1, 2) arguments and named arguments.

A few examples of padding and alignment:

var sprintf=require("sprintf-js").sprintf;

console.log(sprintf("Space Padded => %10.2f", 123.4567));
console.log(sprintf("    _ Padded => %'_10.2f", 123.4567));
console.log(sprintf("    0 Padded => %010.2f", 123.4567));
console.log(sprintf(" Left align => %-10.2f", 123.4567));

Results:

Space Padded =>     123.46
    _ Padded => ____123.46
    0 Padded => 0000123.46
 Left align => 123.46    
4
  • 5
    util.format is better than nothing. But, not much better. :) If it was just part of console.log ... then it would make more sense. Nov 7, 2013 at 17:35
  • I added a few examples to round out the answer. Nov 7, 2013 at 17:47
  • how do i pass a string?
    – chovy
    Sep 14, 2016 at 7:09
  • @chovy-the docs have a lot of examples and I'd suggest you start there. Sep 14, 2016 at 10:35
7

If you have simpler needs you can look into util.format. It can generate string from various parameters. If you want printf like formatting you can use either sprintf package or sprintf-js package.

2
  • 2
    Seems just like my answer? :) Nov 7, 2013 at 14:46
  • Yeah, just few minutes late.
    – user568109
    Nov 7, 2013 at 14:49
3

Take a look at Log4JS, which is an attempt at a functional port of Log4j

3

You might also like string-kit and terminal-kit.

https://www.npmjs.com/package/string-kit

https://www.npmjs.com/package/terminal-kit

https://blog.soulserv.net/terminal-friendly-application-with-node-js-part-ii-moving-and-editing/

1
  • 5
    Hey! Welcome to Stack Overflow! Although the link may contain the answer to the question, make sure you provide the essential information on your answer, so that if that link is ever taken down, the answer is still valid. Thanks! Mar 15, 2017 at 4:38
2

If I combine util.format and "".padStart/"".padEnd together,as described in posts above, then I get what I wated:

> console.log(util.format("%s%s","Name:".padEnd(10), "John Wall"))
Name:     John Wall
1

A version of console.table for NodeJS with align.

⚠ This is only for console version! ⚠

/**
 * @param {NonNullable<{
 *    [key: string]: string
 *  }>} data
 */
const consoleTable = (data) => {
  if (typeof data === 'object') {
    const e = Object.entries(data);
    let kl = 0;
    let vl = 0;

    for (const [k, v] of e) {
      if (k.length > kl) {
        kl = k.length;
      }

      const s = JSON.stringify(v);
      const l = s ? s.length : 0;

      if (l > vl) {
        vl = l;
      }
    }

    /** @type {{ [key: string] : string }} */
    const result = {};

    for (const [k, v] of e) {
      const s = JSON.stringify(v);
      result[k.padStart(kl)] = s ? s.padEnd(vl) : v;
    }

    console.table(result);
  } else {
    console.table(data);
  }
};

Output example:

┌─────────────────┬────────────────────────────────────────────────────────────────────────────────────────┐
│     (index)     │                                         Values                                         │
├─────────────────┼────────────────────────────────────────────────────────────────────────────────────────┤
│     CONFIG_FILE │ '"/Users/ecuomo/projects/zzzzz/xxxxxxxx/tttttttttt-web/jjjjjjjjjj-commons/config.env"' │
│        NODE_ENV │ '"development"                                                                       ' │
│         APP_ENV │ '"local-dev-edu"                                                                     ' │
│     APP_VERSION │ '"0-local-ecuomo"                                                                    ' │
│        BASE_URL │ '"http://localhost:3000"                                                             ' │
│    CDN_BASE_URL │ '"http://localhost:3000/static"                                                      ' │
│    API_BASE_URL │ '"http://localhost:3000/api"                                                         ' │
│           MONGO │ '"mongodb://mongo:27017/xxxxxxxxxxprod"                                              ' │
│      MYSQL_HOST │ '"mysql"                                                                             ' │
│      MYSQL_PORT │ '3306                                                                                ' │
│    MYSQL_DB_ETL │ '"xxxxxxxxxx_etl"                                                                    ' │
│  MYSQL_DB_STATS │ '"xxxxxxxxxx_stats"                                                                  ' │
│ MYSQL_DB_ZAPIER │ '"xxxxxxxxxx_yyyyyy"                                                                 ' │
│   POSTGRES_HOST │ '"postgres"                                                                          ' │
│   POSTGRES_PORT │ '5432                                                                                ' │
│     POSTGRES_DB │ '"xxxxxxxxxx"                                                                        ' │
│      REDIS_HOST │ '"redis"                                                                             ' │
│      REDIS_PORT │ '"6379"                                                                              ' │
│    REDIS_MASTER │                                       undefined                                        │
│      REDIS_MODE │ '"single"                                                                            ' │
└─────────────────┴────────────────────────────────────────────────────────────────────────────────────────┘

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.