节点和小胡子的一个简单例子

时间:2013-09-10 22:31:52

标签: javascript json node.js mustache

好的,简单的例子(基于一本书),但它似乎没有起作用,或者我遗漏了一些明显的东西。 (顺便说一句,我不知道jQuery;我是节点和javascript的新手。)

目标:使用小胡子来呈现html页面以填充其身体部位的内容。对于正文部分,我只想使用JSON消息。该页面由节点提供。

(请告诉我代码,但它主要是标准的。)

档案basic.html

<!DOCTYPE html public "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>A Title</title>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.2/mustache.min.js" type="text/javascript"></script>
    <script src="http://localhost:8000/scripts/{{PAGE_NAME}}.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>

文件模板/ home.html(填充上面的正文部分):

<div id="theData">
    <p>Hello!</p>
    <p>There are {{ fewObjects.length }} objects.</p>
</div>

文件脚本/ home.js(可能是为了在basic.html的body部分内加载home.html的内容而执行的jQuery):

$(document).ready(function (){
    var tmpl,       // Main template HTML
    tdata = {};     // JSON data object that feeds the template

    // Initialize page
    var initPage = function () {
        // Load the HTML template
        $.get("/templates/home.html", function (d) {
            tmpl = d;
        });

        // Retrieve the server data and then initialize the page
        $.getJSON("/objects.json", function (d) {
            $.extend(tdata, d.data);
        })

        // When AJAX calls are complete parse the template
        // replacing mustache tags with vars
        $(document).ajaxStop(function () {
            var renderedPage = Mustache.to_html(tmpl, tdata);
            $("body").html(renderedPage);
        })
    }
});

现在要在节点上运行的文件:

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

var i, temp;
var myObjects = new Array ();

for (i = 0; i < 4; i++) {
    var temp = {};
    temp["x"] = i + 1;
    temp["y"] = 2 * (i+1);
    myObjects.push(temp);
}

var s = http.createServer(demoRequestHandler);
s.listen(8000);
console.log ("Now listening to port " + 8000);
console.log ("------------------------------");

/**************************************************************************************/

function demoRequestHandler (req, res) {
    // parse the url
    req.parsed_url = url.parse (req.url, true);
    var core_url   = req.parsed_url.pathname;
    console.log("INCOMING REQUEST (demo): method is " + req.method + ", url is " + req.url + ", and with core url is " + core_url);

    if (core_url.substring(0, 11) == "/templates/") {
        serve_static_file ("templates/" + core_url.substring(11), res);
    }
    else if (core_url.substring(0, 9) == "/scripts/") {
        serve_static_file ("scripts/" + core_url.substring(9), res);
    }
    else if (core_url == "/home") {
        serve_page (req, res, core_url);
    }
    else if (core_url == "/objects.json") {
        handle_list_objects (req, res);
    }
    else {
        send_failure (res, 404, invalid_resource());
    }
}

function handle_list_objects (req, res) {
    send_success (res, {"fewObjects": myObjects});
}

function serve_page (req, res, core_url) {
    if ((req.method.toLowerCase() == "get") && (core_url == "/home")) {
        // This is the valid address
        fs.readFile(
            "basic.html",
            function (err, contents) {
                if (err) {
                    send_failure (res, 500, err);
                    return;
                }

                contents = contents.toString("utf8");

                contents = contents.replace("{{PAGE_NAME}}", "home");
                res.writeHead (200, { "Content-Type" : "text/html" });
                res.end (contents);
            }
        );
    }
    else {
        send_failure (res, 404, invalid_resource ());
    }
}

function serve_static_file (file, res) {
    fs.exists (file, function (exists){
        if (!exists) {
            res.writeHead (404, {"Content-Type" : "application/json"});
            var out = make_error ("not_found", "'" + file + "' not found");
            res.end(JSON.stringify(out) + "\n");
            return;
        }

        var rs = fs.createReadStream(file);

        rs.on (
            "error",
            function (r) {
                res.end();
            }
        );

        var ct = content_type_for_file(file);
        console.log ("Content-Type = " + ct);
        res.writeHead(200, {"Content-Type" : ct});
        rs.pipe(res);
    });
}

/**************************************************************************************/

function send_success (res, mydata) {
    res.writeHead (200, {"Content-Type" : "application/json"});
    var output = {"error": null, "data": mydata};
    res.end(JSON.stringify(output) + "\n");
}
function send_failure (res, code, err) {
    var code = (err.code) ? err.code : err.name;
    res.writeHead (code, {"Content-Type" : "application/json"});
    res.end(JSON.stringify({"error": code, "message": err.message}) + "\n");
}
function make_error (errCode, msg) {
    var e = new Error(msg);
    e.code = errCode;
    return e;
}
function invalid_resource () {
    return make_error ("invalid_resource", "the requested resource does not exist");
}

/**************************************************************************************/

function content_type_for_file(file) {
    var ext = path.extname(file);
    console.log ("TYPE: file = " + file + ", ext = " + ext);
    switch (ext.toLowerCase()) {
        case ".html": return "text/html";
        case ".js": return "text/javascript";
        case ".css": return "text/css";
        case ".jpg": case ".jpeg": return "image/jpeg";
        default: return "text/plain";
    }
}

0 个答案:

没有答案