0

There are many tutorials for server nodejs + express. You can simply write res.render(somefile) and express show the html page. but how to do it in plain nodejs, how to render pages? I can't find the answer at http://www.nodebeginner.org/

I wrote simple server, but don't know how fix it for my needs:

var http = require("http");
var url = require("url");
var fs = require("fs");



function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    var filename = 'gallery/index.html';
    fs.readFile(filename, function(err, file) {
        if(err) {
            response.writeHead(500, {"Content-Type": "text/plain"});
            response.write(err + "\n");
            response.close();
            return;
        }

        response.writeHead(200, {"Content-Type": "text/html"});
        response.write(file);
        response.end();
    });
}

    http.createServer(onRequest).listen(8888);
    console.log("Server has started.");

This code is simply render one page - gallery/index.html, but render it without images coz can't find them, but how to render directories? for example I want to see index.html in my gallery directory, in apache if I write http://localhost:8888/gallery/ - I will receive index.html page from directory "gallery", how to make the same in node.js?

UPDATE: I solved my problem with node-static module, this answer was very helpful for me https://stackoverflow.com/a/6162856/2560165

Community
  • 1
  • 1
user2560165
  • 149
  • 1
  • 2
  • 15
  • [Connect Static](http://www.senchalabs.org/connect/static.html) is a good reference if you want to implement your own static server. – bnuhero Mar 11 '14 at 08:55
  • If you want to roll your own, here is a good start: https://gist.github.com/hectorcorrea/2573391 But long term I would use Connect Static or another already built module. – Hector Correa Mar 11 '14 at 12:12

3 Answers3

0

i think you need to take a loot at http://expressjs.com/ framework, especcialy on code of router - https://github.com/visionmedia/express/tree/master/lib/router

vodolaz095
  • 6,680
  • 4
  • 27
  • 42
0

When calling res.render(somefile) what express does is to render a HTML template file(default being Jade). Take a look in the views folder and you'll find the *.jade template files there.

If you would like to do it yourself you simply need to come up with a template with a lot of placeholders:

<html>
  <head/>
  <body>
    <h1>Hello {name}</h1>
  </body>
</html>

and then replace the placeholder(in this case {name}) with real values.

saladinxu
  • 372
  • 1
  • 2
  • 12
0

I solved my problem with node-static module, this answer was very hlpful for me https://stackoverflow.com/a/6162856/2560165

Community
  • 1
  • 1
user2560165
  • 149
  • 1
  • 2
  • 15