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.
First of all, your code needs to call renderIndex()
at some point. Second, unless mustache was seriously rewritten since I last looked at it, mu.compileAndRender
will give you back a string, which you generally need to send using httpResponse
s write
or end
methods. util.pimp
is a typo (though admittedly one that's amusing enough to be admirable); util.pump
is now deprecated, and if you've got a readStream
the preferred way is to call its pipe
method with an argument corresponding to the writeStream
you want to send it to (e.g an httpResponse
).
I think you're trying to learn too much at once; you might be better off first learning how to use express
to handle routing and similar stuff (ignoring express's templating/rendering abilities for the time being) and then, once you've got the hang of it, working on rendering and templating (mustache is so common and popular that you'd think express`s developers would have already integrated it, but for some reason they haven't).