繁体   English   中英

如何传递数组以在html文件中显示? -Node.js

[英]How to pass an array to display it in an html file? - Node.js

我目前正在一个项目上,我的代码有一些问题..

我的问题:我的node.js正在分析txt文件并从中读取坐标..这些坐标应显示在html文件中的图形中..两个代码均已创建,但是如何连接它们?

node.js:

    var fs = require('fs');


function readLines(input, done) {
    var arr = [];
    var remaining = '';

    input.on('data', function(data) {
        remaining += data;
        var index = remaining.indexOf('\n');
        while (index > -1) {
            var line = remaining.substring(0, index);
            remaining = remaining.substring(index + 1);
            func(line);
            index = remaining.indexOf('\n');
        }
    });

    input.on('end', function() {
        if (remaining.length > 0) {
            func(remaining);
            done(arr);
        }
    });

    function func(data) {
        arr.push(data.split(/\s+/g)); //Splitfunktion für Komma 
    }
}


var input = fs.createReadStream('test.txt');
readLines(input, done);

//abschließen 
function done(arr) {

    var obj = {};
    var key1 = arr[0][0];
    var key2 = arr[0][1];
    obj[key1] = [];
    obj[key2] = [];

    arr.shift();

    arr.forEach(function (item) {
        obj[key1].push(item[0]);
        obj[key2].push(item[1]);
    });

    console.log('X:', obj[key1]);
    console.log('Y:', obj[key2])
} 

HTML文件:

<!doctype html>
<html>
    <head> 
    <!-- ... --> 
    </head>
    <body>  
     <!-- ..... --> 
    <script>
        var lineChartData = {
            labels : [380, 390 ..<!--  X-Coordinates here --> 
            datasets : [
                {
                    data : [0.5, 
                            0.6, 
                            0.7,  
                            <!-- Y-Coordinates here --> 
                            ]
                }
            ]

        }

    <!-- ... ---> 
    </script>
   </body>
</html>

希望您能提供帮助!

问候,

JS

我建议您使用expressjs。 使用nodejs创建Web应用程序是非常底层的。 您必须通过节点npm install express ,然后从那里进行npm install express

某些代码被窃取以帮助

var express = require('express');
var app     = express();

app.use(express.bodyParser());
app.set('view engine', 'ejs');
app.register('.html', require('ejs'));
app.get('/', function(req, res) {

    // Handle file reading in here and return object
    res.render('index.html', {obj: obj}); //where object is the obj is the object holding the arrays
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

然后在您的index.html中在脚本标记中执行..

<script>
    console.log(<%= cordinates.obj %>);
</script>

免责声明:我尚未测试过,但这只是为了帮助您

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM