javascript - 这个字符串语法在 JavaScript 中意味着什么?

标签 javascript node.js mongoose export

我目前正在尝试自己学习 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 that exports = 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/

相关文章:

javascript - Sequelize : Foreign key declared, 但没有出现在表中

node.js - 为什么 Heroku 不接受我的 Node.js 版本?

mongoose - 使用 Mongoose .findOne() 验证 jwt token

node.js - mongoose.js 中的架构和子文档

javascript - JavaScript 中的数字值到数组

javascript - 选择 ul 元素内具有相同类的 ul 元素

node.js - 跨文件拆分时使用 router.use 表示路由器未定义参数

javascript - 如何使用 mongoose 保存数组架构?

javascript - 两个功能相互干扰

javascript - 如何重新运行当前$state的 Controller ?