I am new to javascript and node.js and I am experimenting with "highcharts-export-server" where I am trying to get the chart as a base64 string. Here is my highchartstest.js file:
const chartExporter = require("highcharts-export-server");
var chartBase64 = null;
function ProcessChart() {
chartExporter.initPool(); // Initialize the exporter
const chartDetails = {
type: 'png',
options: {
title: {
text: 'My Chart'
},
xAxis: {
categories: ["Jan", "Feb", "Mar", "Apr", "Mar", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
},
series: [{
type: 'line',
data: [1, 3, 2, 4]
},
{
type: 'line',
data: [5, 3, 4, 2]
}
]
}
};
chartExporter.export(chartDetails, (err, res) => {
chartBase64 = new Buffer.from(res.data, 'base64');
//console.log(chartBase64);
chartExporter.killPool();
return chartBase64;
});
}
module.exports.ProcessChart = ProcessChart;
I have a another file called test.js with the following code:
var charts = require('./highchartsTest');
var chartBase = charts.ProcessChart();
console.log(chartBase);
If I run node test.js
the result I get is undefined
in the console.
If I uncomment console.log(chartBase64);
in highchartstest.js
I can see that i get a result. Can someone please help me figure out how I can get this to wait for the processing to complete when I call var chartBase = charts.ProcessChart();
The undefined that you receive is not coming from the callback of the export function. The easiest way to receive a correct base64 string would be to add an argument to the ProcessChart function which is a callback that triggers after the killPool call. The code can look like this:
(highcharts-test.js)
const chartExporter = require('highcharts-export-server');
const ProcessChart = callback => {
chartExporter.initPool(); // Initialize the exporter
const chartDetails = {
type: 'png',
options: {
title: {
text: 'My Chart'
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'Mar', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
series: [{
type: 'line',
data: [1, 3, 2, 4]
}, {
type: 'line',
data: [5, 3, 4, 2]
}]
}
};
chartExporter.export(chartDetails, (err, res) => {
if (res) {
chartExporter.killPool();
callback(res.data);
}
});
}
module.exports.ProcessChart = ProcessChart;
(test.js)
const exporter = require('./highcharts-test.js');
const ProcessChart = exporter.ProcessChart;
ProcessChart(base64 => {
console.log(base64);
process.exit();
});