[Chartjs]-How to use Chart.js in Nodejs?

2👍

I suggest using ChartJS for Node: https://www.npmjs.com/package/chartjs-node

It draws a chart which you can then save to the file system and insert accordingly.

Here’s a snippet of code as an example:

import * as ChartjsNode from 'chartjs-node'; // Import the library

const chartNode = new ChartjsNode(600, 600); // Create an instance with dimensions

const barGraphOptions = {
  type: 'bar',
  data: []
};

// Draw the chart and write the file to the file system
await new Promise(resolve => {
  chartNode
    .drawChart(barGraphOptions)
    .then(() => {
      chartNode.getImageBuffer('image/png');
    })
    .then(() => {
      chartNode.writeImageToFile('image/png', 'some_file.png').then(() => {
        resolve();
      });
    })
    .catch(e => {
      console.log('Caught', e);
    });
});

1👍

ChartJS is an HTML5 based file which is used in front-end development only.
For more information visit this site.

You can refer to this answer if you want to use nodejs to create Charts.

P.S. This question is duplicate to this

0👍

I had the same issue as OP. I couldn’t figure out a way to do it using the standard approach of combining Node Canvas and Chart.JS, but I found using ChartjsNodeCanvas works.

import { CanvasRenderService } from 'chartjs-node-canvas';

canvasRenderService: CanvasRenderService;

async createGraph(data: any) {

    const configuration = {
        type: 'bar',
        data: {
            labels: // Your labels,
            datasets: [
                data
            ]
        },
        options: {
           // Your options
        }
    };

    const canvasRenderService = new CanvasRenderService(300, 500);

    return await canvasRenderService.renderToDataURL(configuration);
    // or return canvasRenderService.renderToBuffer(configuration);
    // or return canvasRenderService.renderToStream(configuration);
}


await this.createGraph(data);

Note, ChartjsNodeCanvas requires ChartJS as a dependency.

Leave a comment