简体   繁体   English

重复的要求暴露了Node.js中的函数/构造函数

[英]Repeated requirements that expose a function/constructor in Nodejs

Ok, I still have not fully understand the best way to require modules in Node that will be shared among several js files. 好的,我仍然没有完全理解在Node中要求将在多个js文件之间共享的模块的最佳方法。 For example: If I have a main app.js and two other files: routes1.js and routes2.js containing (mostly) exported routes that are required in app.js . 例如:如果我有一个主要的app.js和另外两个文件: routes1.jsroutes2.js包含(大部分) app.js中需要的导出路由。

I think we all agree about that if I need – for example – UnderscoreJs. 我认为我们都同意,如果我需要-例如UnderscoreJs。 I just repeat this line of code in every file that needs it. 我只是在需要它的每个文件中重复此行代码。

var _ = require('underscore');

But how about modules that expose a function/constructor, like this: 但是,像这样的公开函数/构造函数的模块呢:

var email = require('powerdrill')('YOURAPIKEY');

If i repeat this code in every file, I end up with three instances of the powerdrill object, right? 如果我在每个文件中都重复此代码,则最终将得到powerdrill对象的三个实例,对吗? Even though this works just fine I cant help feeling this ain't right. 即使这很好,我也忍不住感觉不对。

Or maybe its totaly viable and fine if I just want to require it in a small number of files? 或者,如果我只想在少量文件中要求它,那么它完全可行且很好吗?

Question: For all of you who have been working with Node for a while now, and feel comfortable with the way you require things. 问题:对于已经使用Node一段时间并且对您的需求方式感到满意的所有人。 How do you "solve" case 2 above? 您如何“解决”上述情况2? Maybe there is no right way, but a little guidance would be appreciated. 也许没有正确的方法,但是可以提供一些指导。

You could write your own common module and include that instead. 您可以编写自己的通用模块,然后包括它。 Though, I'd prefer what you're doing already but I guess it's a matter of taste. 虽然,我更喜欢您已经在做的事情,但是我想这是一个品味问题。

This is written without testing it, so it probably is not the right way to do it. 编写本文时并未对其进行测试,因此它可能不是正确的方法。 Maybe you'll get some ideas: 也许您会得到一些想法:

// utils.js
// ======== define the module
var myEmail = require('powerdrill')('YOURAPIKEY');
module.exports = {
  email: myEmail
};


// app.js
var utils = require('./utils');
utils.mail.useIt();

This way, I think everyone that requires utils.js will use the same myEmail instance. 这样,我认为每个需要utils.js的人都将使用相同的myEmail实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM