上下文
我在learnyounode中遇到了练习
npm install -g learnyounode
称为 HTTP JSON API 服务器。 练习目标:
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
我无法解决这个问题,我认为这是由于缺乏一些特定的 API 知识,所以我查找了一个解决方案,并发现了这个(顺便说一句,效果很好):
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]));
实际问题
我看着这个片段,愣住了。
if (/^\/api\/parsetime/.test(req.url))
result = parsetime(time);
else if (/^\/api\/unixtime/.test(req.url))
result = unixtime(time);
有人能解释一下 /^\/api\/parsetime/.test(req.url)
到底是做什么的吗?乍一看它看起来像某种正则表达式,但我从未见过 RegExp 可以调用方法。我猜想这是某种形式的识别 URL 路径,但猜想在工业界没有多大值(value)。
先谢谢大家了!
最佳答案
看起来好像
if (/^\/api\/parsetime/.test(req.url))
result = parsetime(time);
else if (/^\/api\/unixtime/.test(req.url))
result = unixtime(time);
正在调用一个函数,但它只是生成一个字符串输出,实际调用者调用的 .test() 将其转换为真实的表达式。
有关 javascript 正则表达式的更多信息,请参阅 https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
关于javascript - HTTP JSON API SERVER 中的这段代码在 learnyounode 中起到了什么作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33196792/