[英]How to pass an array to display it in an html file? - Node.js
I'm currently working on a project and having some issues with my code .. 我目前正在一个项目上,我的代码有一些问题..
My problem: My node.js is analysing a txt file and reading coordinates out of it .. those coordinates should be displayed in a graph in an html file .. both codes are created, but how do I connect them? 我的问题:我的node.js正在分析txt文件并从中读取坐标..这些坐标应显示在html文件中的图形中..两个代码均已创建,但是如何连接它们?
node.js: 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 file: 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>
I hope you can help! 希望您能提供帮助!
Greetings, 问候,
JS JS
I suggest you use expressjs. 我建议您使用expressjs。 Using nodejs
to create web application is quite low-level. 使用nodejs
创建Web应用程序是非常底层的。 You have to install express via node npm install express
and go from there. 您必须通过节点npm install express
,然后从那里进行npm install express
。
Some code snipped to help 某些代码被窃取以帮助
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/');
});
then in your index.html do .. inside script tags. 然后在您的index.html中在脚本标记中执行..
<script>
console.log(<%= cordinates.obj %>);
</script>
DISCLAIMER: I haven't tested this but it's just to help you on your way 免责声明:我尚未测试过,但这只是为了帮助您
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.