Node.js formatted console output

后端 未结 6 600
说谎
说谎 2021-01-31 13:24

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?

6条回答
  •  遥遥无期
    2021-01-31 14:00

    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    
    

提交回复
热议问题