什么是dir? dir +“/”:“”是什么意思?

时间:2014-05-12 15:54:07

标签: javascript

我正在学习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的作用(以及为什么":""")?

2 个答案:

答案 0 :(得分:2)

localPath += (dir ? dir + "/" : "") + filename;

的简写
if (dir) {
    localPath += (dir + "/") + filename;
} else {
    localPath += ("") + filename;
}

这是ternary operator,更具体地说是?: ternary operator

P.S。为清楚起见,我将括号/括号留在等效代码中。

答案 1 :(得分:0)

等于:

if(dir){
  localPath += dir + "/";
}
else{
  localPath += "";
}