Apexcharts save stream response from post request on file Node

Heyo! I’m new using this API and I’m having an issue when trying to write a png file with the stream response.

Can anyone help me save this file locally, like using fs from Node? I have just a script, and I run this using node src/..., I’m not creating an API.

Hey @cranel, can you share the code you’re using to fetch the image and write it to disk? That will help me debug.

1 Like

Hey @ian, ty for your fast answer, I figure out the problem. I was not setting the responseType as stream, then I couldn’t do a pipe on the response.
This is my final code and work well:

Now I’m able to save the file at the root directory, but I’m stucked in another problem. I changed the approach from GET to POST because the formatter function was not working in the first case, so I figured maybe it would work if I used the POST request, but well, didn’t work. Do you have any advice for this?

I believe the issue here is that the POST endpoint expects a valid JSON payload, but the formatter function is not JSON.

Can you make options a string and see how that works? You should be able to do this by putting backticks around it:

const options = `{
  ...
}`

There is some discussion of this here: Using Javascript functions | QuickChart even though this page is written for the main Chart.js API, not Apex Charts.

1 Like

I tried this approach and receive a very big error message
The code:

import axios from 'axios';
import fs from 'fs';

async function generateChart() {
  const options = `{
    chart: {
      type: 'line'
    },
    title: {
      text: 'Test',
    },
    series: [{
      name: 'sales',
      data: [31, 40, 35, 50, 49, 60, 70, 91, 125]
    }],
    xaxis: {
      categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]
    },
    yaxis: {
      labels: {
        formatter: function (value: any) {
          return 'value.toFixed(2)' + '$'
        }
      }
    },
  }`

  const response = await axios.post('https://quickchart.io/apex-charts/render', {
    config: options
  }, {
    responseType: 'stream'
  });

  response.data.pipe(fs.createWriteStream('test.png'))
    .on('finish', () => console.log('written'))
    .on('error', () => console.log('error'));
}

generateChart();

The response

I think the Typescript annotation is the issue. I’ve tried your chart successfully with the following (note that I removed the type):

{
  // ...
  formatter: function (value) {
    return 'value.toFixed(2)' + '$'
  }
}
1 Like

Oh, thank you bro! All working perfectly!!
I have another question but I asked it on another channel as the topic is different. Maybe you can help me with that, too?

Hi Cranel,

Unfortunately the Apex Charts renderer doesn’t have as many fonts as the Chart.js renderer. I believe it only supports sans, serif, and mono at the moment.

I will make sure that expanding font selection is added to our roadmap :slight_smile:

1 Like

Oh, right, no problem! Thx for the answer!