最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Charting in the terminal commander C:I - Stack Overflow

programmeradmin5浏览0评论

I intend to take up a project that builds out a CLI using mander that makes requests to an API.

I am wondering how I would go about adding basic charts in the terminal that are similar to and a graph functionality in the terminal (similar to the GitHub contributions graph).

I am unable to find good npm packages for this (a Python alternative for this is termgraph), any help is appreciated.

I intend to take up a project that builds out a CLI using mander that makes requests to an API.

I am wondering how I would go about adding basic charts in the terminal that are similar to and a graph functionality in the terminal (similar to the GitHub contributions graph).

I am unable to find good npm packages for this (a Python alternative for this is termgraph), any help is appreciated.

Share Improve this question edited Nov 21, 2024 at 19:54 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 20, 2020 at 17:11 Rohit SinghRohit Singh 611 silver badge3 bronze badges 1
  • Not sure of any ready made solutions, but using something like npmjs./package/chalk should be pretty easy to do – Keith Commented Dec 20, 2020 at 20:14
Add a ment  | 

2 Answers 2

Reset to default 7

I don't know any package that display chart for the terminal, however, this can be done all by you using chalk.

This package allow you to display color within the terminal, it will be your job to format the console.log so it get printed with the right colors and width.

Otherwise, a quick search on npm, using terminal+chart keyword gave me the following interesting results:

  • ervy
  • cli-pie
  • cli-chart
  • terminal-bar
  • ascii-chart
  • asciichart

As @Dimitri suggested, you can take a look at a simple example using the chalk package for Node.js.

chart.js:

import chalk from 'chalk';

const rankingsData = {
  "Rankings": [
    8267,
    10747
  ],
  "Long Rankings": [
    6150,
    10494
  ],
  "Short Rankings":[
    0,
    3670
  ]
}

// Calculate the maximum value in the set. Will be used in normalization (see below):
const max = Math.max(...Object.values(rankingsData).flat());

// Helper function to 'normalize' values down to 100% according to min/max:
function normalize(value){
  return ( Math.floor((((value - 0) / (max - 0)) * 100)/2) )
}

Object.entries(rankingsData).forEach((([key, [first, second]])=>{

  const firstLength = " ".repeat(normalize(first));
  const secondLength = " ".repeat(normalize(second));

  console.log(
    key.padEnd(15," ") + ":", 
    chalk.bgBlue.bold(firstLength), 
    first + ".00"
  );
  console.log(
    " ".padEnd(16," "), 
    chalk.bgRed.bold(secondLength), 
    second + ".00"
  );
  // console.log("\n");
}));
$ npm install chalk
$ node chart.js

发布评论

评论列表(0)

  1. 暂无评论