Pas*_*Qyy 5 connect node.js express
我是Node.js世界的新手
根据这个主题:什么是Node.js的Connect,Express和"中间件"?
我了解到Connect是Express的一部分
我在代码中挖了一点,我发现了两个非常有趣的文件:
./myProject/node_modules/express/lib/utils.js
Run Code Online (Sandbox Code Playgroud)
更好的:
./myProject/node_modules/express/node_modules/connect/lib/utils.js
Run Code Online (Sandbox Code Playgroud)
这两个文件充满了有用的功能,我想知道如何正确调用它们.
到目前为止,./myProject/app.js
这就是我所做的:
var express = require('express')
, resource = require('express-resource')
, mongoose = require('mongoose')
, expresstUtils =
require('./node_modules/express/lib/utils.js');
, connectUtils =
require('./node_modules/express/node_modules/connect/lib/utils.js');
Run Code Online (Sandbox Code Playgroud)
但我发现它有点笨拙,那我的其他文件怎么样?
例如,这是我的一条路线:
myResources = app.resource(
'myresources',
require('./routes/myresources.js'));
Run Code Online (Sandbox Code Playgroud)
这是以下内容myresources.js
:
exports.index = function(req, res)
{
res.render('./myresources.jade', { title: 'My Resources' });
};
exports.show = function(req, res)
{
fonction resourceIsWellFormatted(param)
{
// Here is some code to determine whether the resource requested
// match with the required format or not
// return true if the format is ok
// return false if not
}
if (resourceIsWellFormatted(req.params['myresources']))
{
// render the resource
}
else
{
res.send(400); // HEY! what about the nice Connect.badRequest in its utils.js?
}
};
Run Code Online (Sandbox Code Playgroud)
正如您在后面的注释中所看到的res.send(400)
,我问自己是否可以使用Connect模块文件中的badRequest
函数utils.js
.
md5
同一个文件中的好功能怎么样?
在我开始myresources.js
使用它时,我是否必须放置这个可怕的电话?
var connectUtils =
require('../node_modules/express/node_modules/connect/lib/utils.js');
Run Code Online (Sandbox Code Playgroud)
或者,是否有更优雅的解决方案(即使是app.js
)?
预先感谢您的帮助!
小智 2
我想出的唯一更优雅的方法是(假设express位于你的根“node_modules”文件夹中):
require("express/node_modules/connect/lib/utils");
Run Code Online (Sandbox Code Playgroud)
节点安装在Windows上,节点版本0.8.2
和一些额外的信息:
这样您就不需要知道您在路径中的位置并被迫使用相对路径(./ 或 ../),这可以在任何文件嵌套级别上完成。
我将所有自定义模块放在根“node_modules”文件夹中(我将文件夹命名为“custom_modules”),并在任何嵌套级别都以这种方式调用它们:
require("custom_modules/mymodule/something")
Run Code Online (Sandbox Code Playgroud)