SRR
SRR

Reputation: 1758

How to print box around characters in terminal - Node.js

I currently have these lines of code to print information out in a box in the terminal:

  `
  \t\t   ╭───────────────────────────────────────╮
  \t\t   │                                       │
  \t\t   │   Server @ ${version}                      │
  \t\t   │                                       │
  \t\t   │   ▸ Name      :   ${serverName}             │
  \t\t   │   ▸ Network   :   ${isNetwork ? "Yes" : "No"}                 │
  \t\t   │   ▸ Internet  :   ${isInternet ? "Yes" : "No"}                 │
  \t\t   │   ▸ Device IP :   ${ip.address()}       │
  \t\t   │                                       │
  \t\t   │                                       │
  \t\t   │   ${`Listening: http://localhost:${port}/`)}   |
  \t\t   │                                       │
  \t\t   ╰───────────────────────────────────────╯
  `

The lines above give the below result with me manually moving the lines.

           ╭───────────────────────────────────────╮
           │                                       │
           │   Server @ 1.1.0                      │
           │                                       │
           │   ▸ Name      :   Equinox             │
           │   ▸ Network   :   Yes                 │
           │   ▸ Internet  :   Yes                 │
           │   ▸ Device IP :   x.x.x.x             │
           │                                       │
           │                                       │
           │   Listening: http://localhost:6500/   |
           │                                       │
           ╰───────────────────────────────────────╯

Is there any way to programmatically insert the box so that I don't have to count characters and manually place the lines?

Upvotes: 0

Views: 2371

Answers (2)

esqew
esqew

Reputation: 44713

If you're ok with adding a dependency, something like node-cli-box could do the trick:

var Box = require("cli-box");

const version = 'v1.0.0';
const serverName = 'ServerName';
const isNetwork = true;
const isInternet = true;
const ip = {
  address: function() { return '127.0.0.1' }
};
const port = 8080;

const myBox = new Box({
  w: 50,
  h: 10,
  stringify: false,
  marks: {
    nw: '╭',
    n: '─',
    ne: '╮',
    e: '│',
    se: '╯',
    s: '─',
    sw: '╰',
    w: '│'
  },
  hAlign: 'left',
}, `Server @ ${version}
▸ Name      :   ${serverName}
▸ Network   :   ${isNetwork ? "Yes" : "No"}
▸ Internet  :   ${isInternet ? "Yes" : "No"}
▸ Device IP :   ${ip.address()}

Listening: http://localhost:${port}/`);
console.log(myBox.stringify());

Repl.it

Upvotes: 2

selfagency
selfagency

Reputation: 1578

Algorithmically, the way to do it would be to determine the length of the longest line of text that will appear within the box and then set the length of your border to pad around that. However, there does appear to be a Node module called node-cli-box that will do this for you.

Upvotes: 1

Related Questions