2014-01-23 13 views
0

我目前正在研究一個項目,並與我的代碼有一些問題..如何傳遞數組以將其顯示在html文件中? - 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

+0

我想你應該看看[expressjs(http://expressjs.com/) – dcodesmith

回答

0

我建議你使用expressjs。使用nodejs創建Web應用程序是相當低級的。你必須通過節點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標籤內。

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

免責聲明:我沒有測試過這一點,但它只是爲了幫助你的方式

+0

嗨dcodesmith ,這已經幫了很多!你用{coordinates:obj}表示什麼意思? - > obj [key1]和obj [key2]都是X和Y座標..你知道如何將它們分別發送到index.html嗎? – JSt

+0

你不需要單獨發送它們,你可以在html中訪問它們。 – dcodesmith

+0

好吧,服務器啓動時沒有錯誤,它起作用,但是當我查看html文件的源代碼時,我看到了放置console.log(<%= cordinates.obj%>):console的位置。日誌(未定義); .. 任何想法? – JSt

相關問題