好的,简单的例子(基于一本书),但它似乎没有工作,或者我错过了一些明显的东西。(顺便说一句,我不知道 jQuery;我对节点和 javascript 都是新手。)
目标:呈现一个使用 mustache 填充其正文部分内容的 html 页面。对于正文部分,我只想使用 JSON 消息。该页面由节点提供。
(请忍受我的代码,但它主要是标准的。)
文件基本.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>
文件 templates/home.html(用于填充上述正文部分):
<div id="theData">
<p>Hello!</p>
<p>There are {{ fewObjects.length }} objects.</p>
</div>
文件 scripts/home.js(大概是执行加载 home.html 内容到 basic.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";
}
}