0

I am learning Node.js, and learning advanced Javascript. In this code, they use Node for making a HTTP Server, all is ok and easy:

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);

But, I do not understand what the construct dir ? dir does (and why " :"" ")?

Matt
  • 70,063
  • 26
  • 142
  • 172
gurrumo
  • 73
  • 2
  • 9
  • 3
    [Conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) – p.s.w.g May 12 '14 at 15:55

2 Answers2

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

is a shorthand for

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

This is ternary operator, more specifically the ?: ternary operator.

P.S. I have left the parenthesis/braces in the equivalent code for clarity.

Zlatin Zlatev
  • 2,670
  • 21
  • 30
0

Is equal to:

if(dir){
  localPath += dir + "/";
}
else{
  localPath += "";
}
TheGr8_Nik
  • 2,790
  • 1
  • 14
  • 29