/
node-highcharts.js
101 lines (84 loc) · 2.42 KB
/
node-highcharts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
var jsdom = require('jsdom'),
spawn = require('child_process').spawn;
function createHighchartsWindow(callback) {
var window = jsdom.jsdom().parentWindow,
script = window.document.createElement('script');
// Convince Highcharts that our window supports SVG's
window.SVGAngle = true;
// jsdom doesn't yet support createElementNS, so just fake it up
window.document.createElementNS = function(ns, tagName) {
var elem = window.document.createElement(tagName);
elem.getBBox = function() {
return {
x: elem.offsetLeft,
y: elem.offsetTop,
width: elem.offsetWidth,
height: elem.offsetHeight
};
};
return elem;
};
// Load scripts
jsdom.jQueryify(window, 'http://code.jquery.com/jquery-1.4.2.min.js', function(w,jq) {
var filename = 'file:///' + __dirname + '/highcharts/highcharts.src.js';
script.src = filename;
script.onload = function() {
callback(window);
}
window.document.body.appendChild(script);
});
}
function serverifyOptions(options) {
options.chart.renderTo = 'container';
options.chart.renderer = 'SVG';
options.chart.animation = false;
options.series.forEach(function(series) {
series.animation = false;
});
}
function render(options, callback) {
createHighchartsWindow(function(window) {
try {
var $ = window.jQuery,
Highcharts = window.Highcharts,
document = window.document,
$container = $('<div id="container" />'),
chart, svg, convert, buffer;
$container.appendTo(document.body);
serverifyOptions(options);
try {
chart = new Highcharts.Chart(options);
} catch (e) {
callback(e, null);
return;
}
svg = $container.children().html();
// Start convert
convert = spawn('convert', ['svg:-', 'png:-']);
// Pump in the svg content
convert.stdin.write(svg);
convert.stdin.end();
// Write the output of convert straight to the response
convert.stdout.on('data', function(data) {
try {
var prevBufferLength = (buffer ? buffer.length : 0),
newBuffer = new Buffer(prevBufferLength + data.length);
if (buffer) {
buffer.copy(newBuffer, 0, 0);
}
data.copy(newBuffer, prevBufferLength, 0);
buffer = newBuffer;
} catch (err) {
callback(err, null);
}
});
// When we're done, we're done
convert.on('exit', function(code) {
callback(null, buffer);
});
} catch (err) {
callback(err, null);
}
});
}
exports.render = render;