我正在创建一个从 http://services.swpc.noaa.gov/text/ace-swepam.txt 获取实时数据的网站,我希望它使用 chart.js 将此数据输出到图表。我有时间、日期(所有字段)质子密度、体积速度和阵列中的 ionic 温度,但我无法弄清楚如何在此设置中使用 chart.js。到目前为止,我所成功完成的是
npm install chart.js
是在设置方面吗?
我知道我需要用 Javascript 设置图表和数据,并用 HTML 绘制 Canvas 。但是我不知道把js/css放在哪里。我试过将它放在代码的 response.write() 部分的脚本标签内,但即使在双引号内使用所有单引号,它仍然搞砸了,告诉我事情是非法的。
我还尝试使用 fs.readFile 制作一个单独的 html 页面,其中包含我需要的所有 Javascript 和 CSS,但是我不知道如何在 html 中使用来自 Node 的数据数组。
// console.log(year, month, day, time, statusno, proton, bulksp, iontemp);
http.createServer(function (request, response) {
//works but I can't pass values into it
fs.readFile('index.html',function (err, data){
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
//Doesn't like it when I try adding more complicated code (like javascript etc)
// response.write('<html>\n<head>\n<title>Solar Activity</title>\n</head>\n<body>'+iontemp+'</body>\n</html>');
response.end();
});
}).listen(8124);
最佳答案
注意:您应该使用某种模板引擎。
下面只是证明这是可能的
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script>
// ** entire Chart.js library **
</script>
<style>
</style>
</head>
<body>
<canvas id="myChart"></canvas>
<script>
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: {{chartData}}
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(data);
</script>
</body>
</html>
注意占位符 {{chartData}}
。另请注意,您必须替换 Chart.js 文件中的实际脚本(您可以链接到脚本文件,但随后您将需要一个提供静态文件的模块)
example.js
var http = require('http');
var fs = require('fs');
http.createServer(function (req, response) {
fs.readFile('index.html', 'utf-8', function (err, data) {
response.writeHead(200, { 'Content-Type': 'text/html' });
var chartData = [];
for (var i = 0; i < 7; i++)
chartData.push(Math.random() * 50);
var result = data.replace('{{chartData}}', JSON.stringify(chartData));
response.write(result);
response.end();
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
我们只需用实际数据替换占位符。
关于javascript - 在 node.js 中使用 chart.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32092676/