Ketus Ketus - 1 year ago 76
HTTP Question

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


I've come across excercise in learnyounode

npm install -g learnyounode

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:


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' });
} else {


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
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download