Created
June 1, 2017 14:50
-
-
Save hparadiz/c20cc3fa1cf9aba7497a7fe89594bf65 to your computer and use it in GitHub Desktop.
Test for chartjs-node npm module which checks if a file is ready after writing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ChartjsNode = require('chartjs-node'); | |
const fs = require('fs'); | |
const tmp = require('tmp'); | |
charts = { | |
drawLineChart: function(options,onFinish) { | |
var width = options.width ? options.width : 700; | |
var height = options.height ? options.height : 400; | |
delete options.width, options.height; | |
var chartNode = new ChartjsNode(width, height); | |
var filename = tmp.tmpNameSync({template: '/tmp/tmp-XXXXXX.png'}); | |
return chartNode.drawChart(options).then(() => { | |
return chartNode.getImageBuffer('image/png'); | |
}).then(buffer => { | |
Array.isArray(buffer) // => true | |
// as a stream | |
return chartNode.getImageStream('image/png'); | |
}) | |
.then(streamResult => { | |
// using the length property you can do things like | |
// directly upload the image to s3 by using the | |
// stream and length properties | |
//streamResult.stream // => Stream object | |
//streamResult.length // => Integer length of stream | |
// write to a file | |
return chartNode.writeImageToFile('image/png', filename); | |
}) | |
.then(() => { | |
if(typeof onFinish == 'function') { | |
onFinish.call(this,filename); | |
} | |
}) | |
} | |
} | |
charts.drawLineChart(chartJsOptions,function(filename) { | |
fs.stat(filename, function(err, stat) { | |
if(err == null) { | |
console.log('Starting upload ' + filename); | |
// upload code goes here | |
} else if(err.code == 'ENOENT') { | |
console.log('System reports ' + filename + ' does not exist.'); | |
} | |
else { | |
console.log('Some other error: ', err.code); | |
} | |
}.bind(this)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment