-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (44 loc) · 1.26 KB
/
index.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
'use strict'
const path = require('path')
const childProcess = require('child_process')
const phantomjs = require('phantomjs-prebuilt')
const crypto = require('crypto')
const os = require('os')
const fs = require('fs')
const render = (options, size = '320x320') => {
return new Promise((resolve, reject) => {
const output = path.join(os.tmpdir(), `chart-${crypto.randomBytes(4).readUInt32LE(0)}.png`)
const childArgs = [
path.join(__dirname, 'exporter.js'),
output,
JSON.stringify(options),
size
]
childProcess.execFile(phantomjs.path, childArgs, (err, stdout, stderr) => {
if (err) {
reject(err)
} else if (stderr !== '') {
reject(new Error(stderr))
} else {
const chunks = []
let totalLength = 0
const fileStream = fs.createReadStream(output)
fileStream.on('data', chunk => {
chunks.push(chunk)
totalLength += chunk.length
})
fileStream.on('end', () => {
fs.unlink(output, err => {
if (err) {
reject(err)
} else {
resolve(Buffer.concat(chunks, totalLength))
}
})
})
fileStream.on('error', reject)
}
})
})
}
module.exports = render