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?

exebook
  • 32,014
  • 33
  • 141
  • 226
  • 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 07 '13 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 07 '13 at 14:35
  • 1
    I was thinking about `printf()` with various handy format modifiers to the output string. – exebook Nov 07 '13 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](https://github.com/vitaly-t/manakin). – vitaly-t Dec 02 '16 at 12:24

8 Answers8

74

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
// }
exebook
  • 32,014
  • 33
  • 141
  • 226
TheChetan
  • 4,440
  • 3
  • 32
  • 41
34

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

DivineCoder
  • 702
  • 5
  • 11
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    
WiredPrairie
  • 58,954
  • 17
  • 116
  • 143
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.

user568109
  • 47,225
  • 17
  • 99
  • 123
3

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

Lee Goddard
  • 10,680
  • 4
  • 46
  • 63
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/

cascading-style
  • 488
  • 9
  • 23
jjstiff
  • 31
  • 2
  • 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! – Matheus Avellar Mar 15 '17 at 04: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
spikeyang
  • 691
  • 9
  • 17
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"                                                                            ' │
└─────────────────┴────────────────────────────────────────────────────────────────────────────────────────┘
Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94