javascript 在 node.js 中使用 chart.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32092676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:50:48  来源:igfitidea点击:

Using chart.js inside node.js

javascriptnode.jschart.js

提问by Leah Scott

I'm creating a site that gets live data from http://services.swpc.noaa.gov/text/ace-swepam.txt, and I want it to output this data to charts using chart.js. I've got the time, date (all fields) proton density, bulk speed and ion temperature in arrays, but I can't figure out how to use chart.js with this set-up. All I've managed to do successfully so far is

我正在创建一个从http://services.swpc.noaa.gov/text/ace-swepam.txt获取实时数据的站点,我希望它使用 chart.js 将此数据输出到图表。我有阵列中的时间、日期(所有字段)质子密度、体积速度和离子温度,但我无法弄清楚如何在此设置中使用 chart.js。到目前为止我成功做的就是

npm install chart.js

is that it in terms of set up?

是在设置方面吗?

I know I need to set up the charts and data in Javascript, and draw the canvas in HTML. But I don't know where to put the js/css. I've tried putting it inside script tags in the response.write() section of the code, but even using all single quotes inside double quotes, it's still messing up and telling me things are illegal.

我知道我需要在 Javascript 中设置图表和数据,并在 HTML 中绘制画布。但我不知道把 js/css 放在哪里。我试过把它放在代码的 response.write() 部分的脚本标签内,但即使在双引号内使用所有单引号,它仍然会搞砸并告诉我事情是非法的。

I've also tried making a separate html page complete with all the Javascript and CSS I need, using fs.readFile, but then I don't know how to use my data arrays from node within the html.

我还尝试使用 fs.readFile 制作一个单独的 html 页面,其中包含我需要的所有 Javascript 和 CSS,但后来我不知道如何从 html 中的节点使用我的数据数组。

 // 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);

回答by potatopeelings

NOTE : You should be using some sort of template engine.

注意:您应该使用某种模板引擎。

The below is just something to show that it's possible

以下只是表明这是可能的



index.html

索引.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>

Notice the placeholder {{chartData}}. Also do note that you have to substitute in the actual script from the Chart.js file (you could link to the script file, but then you'll need a module that serves up static files)

注意占位符{{chartData}}。另请注意,您必须替换 Chart.js 文件中的实际脚本(您可以链接到脚本文件,但随后您需要一个提供静态文件的模块)

example.js

例子.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/');

We simply substitute the placeholder with actual data.

我们只是用实际数据替换占位符。