使用nodeJS从X载入文章到现有的x.html

是的,这里只是另一个NodeJS noob。 我GOOGLE了试图find答案,但由于nodeJS不像PHP一样stream行,所以它不是那么容易。

比方说,我有一个像这样的index.html文件:

<html> <body> <div id="container"> <div id="title">Articles</div> <div id="articles"> <!--Load information from nodeJS--> </div> </div> </body> </html> 

我有一个nodeJS文件,像这样:

 var http = require('http'); var server = http.createServer(function(request, response) { response.write("<div class='articletitle'>ABC</div>"); response.write("<div class='articletext'>This is a test article</div>"); response.end(); }); server.listen(3000); 

我想要什么?

  • 我想从nodeJS输出中获得文章,并把它放到#articles

你需要一个模板引擎。 一个简单的例子就是EJS(与PHP中的知识非常接近),下面是例子(不要忘记用npm来安装):

 var http = require('http'); var ejs = require('ejs'); // create http server http.createServer(function (req, res) { res.writeHead(200, {'content-type': 'text/html'}); // data to render var articles = [{title: 'Hello'}]; // rendering the ejs file ejs.renderFile(__dirname + '/views/articles.ejs', {articles: articles}, function(err, result) { // render on success if (!err) { res.end(result); } else { res.end('An error occurred'); console.log(err); } } ); }).listen(3000); // views/articles.ejs <html> <body> <div id="container"> <div id="title">Articles</div> <div id="articles"> <% articles.forEach(function(article) { %> <h2><%= article.title %></h2> <% }); %> </div> </div> </body> </html> 

你必须使用像haml或jade这样的模板引擎。

另外我会build议使用expressjs。

首先,由于您是NodeJS的新手,我强烈build议您使用ExpressJS框架 。 它封装了大部分通常需要的NodeJSfunction。

轻松实现你想要的最好的方法是使用一些模板引擎 。

例如,你可以使用Jade ,你的代码就像这样:

 html body div#container div#title Articles div#articles each article in articles div.articletitle= article.title div.articletext= article.text 

然后,你的NodeJS(与ExpressJS框架)代码将是这样的:

 app.get('/', function (req, res) { var tmpl = { articles: [ { title: 'ABC', text: 'This is a test article' }, { title: 'XYZ', text: 'Just another random article' } ] }; res.render('index', tmpl); });