1

I'm trying to learn nodejs. I want to serve a static html file using mustache and nodejs. I create a module for start the server with this code :

var http = require("http");
function startServer(){
    function onRequest(request,response){
        console.log("Request received");
        response.writeHead(200, {"Content-type" : "text/html" });
        response.write("hello");
        response.end();
    }
    console.log("The server is running at http://localhost:8888");
    http.createServer(onRequest).listen(8888);
    }

exports.startServer = startServer;

and then I do this on the indexjs file :

var server = require("./server");
var util = require("util");
var fs= require("fs");
var mu = require("mu2");

function renderIndex(){
   var streamIndex = mu.compileAndRender('index.html',{"name" : "Antonio"});
    util.pimp(streamIndex, response);
}

server.startServer(renderIndex);

I know that I'm doing something completely wrong, but can't get where is the error. I tried to merge 2 different tutorials i was reading about nodejs.

P.S: I know that i could use express or other frameworks, but i would like to start using nodejs from scratch to understand how it really works.

4

1 回答 1

3

首先,您的代码需要renderIndex()在某个时候调用。其次,除非自从我上次查看 mustache 以来,它被认真地重写过,否则mu.compileAndRender会返回一个字符串,您通常需要使用httpResponseswriteend方法发送该字符串。util.pimp是一个错字(尽管无可否认,这很有趣,令人钦佩);util.pump现在已弃用,如果您有readStream首选方法是使用与您要发送到pipe的参数相对应的参数调用其方法(例如 an )。writeStreamhttpResponse

我认为你试图一次学习太多;你可能最好先学习如何使用express来处理路由和类似的东西(暂时忽略 express 的模板/渲染能力),然后,一旦你掌握了它的窍门,就开始渲染和模板(小胡子就是这样)你会认为 express 的开发人员已经集成了它,但由于某种原因他们没有集成它)。

于 2012-09-19T10:49:37.860 回答