我目前正在尝试自己学习 Node js,而且我对 javascript 也是完全陌生的。当我尝试阅读和理解 Mongoose 时,我发现了这段代码,没有任何解释。
在router.js
中:
var url = require('url');
var fs = require('fs');
exports.get = function(req, res) {
req.requrl = url.parse(req.url, true);
var path = req.requrl.pathname;
if (/\.(css)$/.test(path)){
res.writeHead(200, {'Content-Type': 'text/css'});
fs.readFile(__dirname + path, 'utf8', function (err, data){
if (err) throw err;
res.write(data, 'utf8');
res.end();
});
} else {
if (path === '/' || path === '/home') {
require('./controllers/home-mongoose').get(req, res);
} else {
require('./controllers/404').get(req, res);
}
}
}
首先,这个 exports.get
是什么?我有点理解 exports = function functionA(){}
意味着当我可以做这样的事情时:
var router = require('path/router.js');
router.functionA();
但是当你执行 exports.get
时,我不明白这意味着什么。
第二,/\.(css)$/.test(path)
。我不明白这个表达式语法,有人可以向我解释一下吗?谢谢
最佳答案
First of all, what is this
exports.get
? I kind of understand thatexports = function functionA(){}
means that when I can do something like this :var router = require('path/router.js'); router.functionA();
exports = function functionA(){}
实际上并没有按照您的想法进行操作。
在 Node 中,exports
只是一个最初引用对象
的变量。并且,该行正在该对象上设置 get
属性/方法。
console.log(exports); // {}
exports.get = function () {};
console.log(exports); // { get: function () {} }
exports
引用的对象通常与 require()
在引用模块/文件时返回的对象相同。
// `router` = `module.exports` from `./path/router.js`
var router = require('./path/router');
router.get()
有关导出
的更多信息,请阅读Modules documentation对于 Node.js
Second,
/\.(css)$/.test(path)
. I don't get this expression syntax, anyone can explain it to me ?
表达式的第一部分 /\.(css)$/
是 RegExp literal .
/
是开始和结束分隔符,其行为与字符串文字周围的引号类似。并且,在它们之间,\.(css)$
是正在定义的模式。
\. // match a single period character
// escaped to disable the period's "any character" meaning
(css) // match the 3 characters, "css", within a capture group
$ // anchor the pattern to the end of the line/string
表达式也可以使用 RegExp
构造函数编写为:
new RegExp("\\.(css)$").test(path) // note the extra escape needed for the string
关于javascript - 这个字符串语法在 JavaScript 中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32899626/