我正试图绕过Node JS的Plotly库。我一直在研究https://github.com/plotly/plotly-nodejs上的一些例子。我需要能够保存绘图的图像,以便然后可以将该图像显示给用户,而不是他们必须转到单独的网站并查看该文件。对此文件的记录方式并不多(或者至少我找不到任何文件!)所以我会盲目飞行。
我创建了一个名为charts.js的模块来尝试测试它,如下所示:
'use strict';
const fs = require('fs');
const plotly = require('plotly')(<username>, <api_key>);
const self = module.exports = {
plotChart: function()
{
let data = [
{
x:[0,1,2],
y:[3,2,1],
type: 'bar'
}];
let layout = {
fileopt : "overwrite",
filename : "simple-node-example"
};
plotly.plot(data, layout, function (err, msg) /** @namespace plotly.plot */
{
if (err) return console.log(err);
console.log(msg);
});
},
writeImage: function()
{
let trace1 = {
x: [1, 2, 3, 4],
y: [10, 15, 13, 17],
type: "scatter"
};
let figure = {
'data': [trace1]
};
let imgOpts = {
format: 'png',
width: 1000,
height: 500
};
plotly.getImage(figure, imgOpts, function (error, imageStream)
{
if (error)
{
return console.log (error);
}
let fileStream = fs.createWriteStream('./public/charts/test.png');
imageStream.pipe(fileStream);
});
}
};
当我测试我的应用时,我使用以下命令尝试编写图像:
charts.writeImage();
当我这样做时,没有任何反应。我检查我的日志(通过Heroku),我看到以下错误:
2018-03-28T14:01:01.224962+00:00 app[web.1]: events.js:183
2018-03-28T14:01:01.224966+00:00 app[web.1]: throw er; // Unhandled 'error' event
2018-03-28T14:01:01.224968+00:00 app[web.1]: ^
2018-03-28T14:01:01.224969+00:00 app[web.1]:
2018-03-28T14:01:01.224971+00:00 app[web.1]: Error: ENOENT: no such file or directory, open './public/charts/test.png'
2018-03-28T14:01:01.285729+00:00 heroku[web.1]: State changed from up to crashed
2018-03-28T14:01:01.287554+00:00 heroku[web.1]: State changed from crashed to starting
2018-03-28T14:01:01.275663+00:00 heroku[web.1]: Process exited with status 1
我是否正确猜测发生此错误是因为目标文件不存在?如果是这样,我如何以编程方式创建此文件?
答案 0 :(得分:0)
只需在if条件中创建一个文件。
if (err.contains("no such file") {
fs.write(filename, data, encoding, function(err) {
console.log(err);
});
}
答案 1 :(得分:0)
不再需要,因为我发现ImageCharts更适合我的需求。