我正在学习Node.js,并学习高级Javascript。在这段代码中,他们使用Node创建HTTP服务器,一切都很简单:
var http = require("http");
var path = require("path");
var fs = require("fs");
var extensions = {
".html": "text/html",
".css": "text/css",
".js": "application/javascript",
".png": "image/png",
".gif": "image/gif",
".jpg": "image/jpeg"
};
http.createServer(function(req, res) {
var filename = path.basename(req.url) || "index.html";
var ext = path.extname(filename);
var dir = path.dirname(req.url).substring(1);
var localPath = __dirname + "/public/";
if (extensions[ext]) {
localPath += (dir ? dir + "/" : "") + filename;
path.exists(localPath, function(exists) {
if (exists) {
getFile(localPath, extensions[ext], res);
} else {
res.writeHead(404);
res.end();
}
});
}
}).listen(8000);但是,我不明白构造dir ? dir是做什么的(为什么是“:")?
发布于 2014-05-12 23:56:33
localPath += (dir ? dir + "/" : "") + filename;是以下的简写:
if (dir) {
localPath += (dir + "/") + filename;
} else {
localPath += ("") + filename;
}这是ternary operator,更具体地说是?: ternary operator。
附注:为了清楚起见,我将括号/大括号留在了等价的代码中。
发布于 2014-05-12 23:56:08
等于:
if(dir){
localPath += dir + "/";
}
else{
localPath += "";
}https://stackoverflow.com/questions/23613560
复制相似问题