Ketus Ketus - 1 month ago 12
HTTP Question

What does this snippet in HTTP JSON API SERVER excercise in learnyounode

Context



I've come across excercise in learnyounode

npm install -g learnyounode


called HTTP JSON API SERVER.
Goal of an excercise:


Write an HTTP server that serves JSON data when it receives a GET request to the path '/api/parsetime'. Expect the request to contain a
query string with a key 'iso' and an ISO-format time as the value.

For example:

/api/parsetime?iso=2013-08-10T12:10:15.474Z


I wasn't able to solve it, which I think is due to lack of some specific API knowledge, so i looked up a solution, and found this (which works fine btw):



var http = require('http');
var url = require('url');

function parsetime (time) {
return {
hour: time.getHours(),
minute: time.getMinutes(),
second: time.getSeconds()
};
}

function unixtime (time) {
return { unixtime : time.getTime() };
}

var server = http.createServer(function (req, res) {
var parsedUrl = url.parse(req.url, true);
var time = new Date(parsedUrl.query.iso);
var result;

if (/^\/api\/parsetime/.test(req.url))
result = parsetime(time);
else if (/^\/api\/unixtime/.test(req.url))
result = unixtime(time);

if (result) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
} else {
res.writeHead(404);
res.end();
}
})

server.listen(Number(process.argv[2]));





Actual question



I looked at this snippet and froze.

if (/^\/api\/parsetime/.test(req.url))
result = parsetime(time);
else if (/^\/api\/unixtime/.test(req.url))
result = unixtime(time);


Could anyone explain what
/^\/api\/parsetime/.test(req.url)
does exactly? At first it looks like some kind of regular expression, but I've never seen that RegExp could invoke methods. I guess that it is some form of identifying URL path, but guess is not worth much in industry.

Thanks everyone in advance!

Answer

It may look as if

if (/^\/api\/parsetime/.test(req.url))
    result = parsetime(time);
else if (/^\/api\/unixtime/.test(req.url))
    result = unixtime(time);

is invoking a function, but it is just generating a string output which the actual invoker called .test() turns into a truthful expression.

For more on javascript regex have a look at https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions