【发布时间】:2013-09-21 18:44:45
【问题描述】:
这是我第二个周末玩 Node,所以有点新手。
我有一个 js 文件,其中包含一些常用实用程序,这些实用程序提供了 JavaScript 不提供的东西。严重剪裁,看起来是这样的:
module.exports = {
Round: function(num, dec) {
return Math.round(num * Math.pow(10,dec)) / Math.pow(10,dec);
}
};
许多其他自定义代码模块——也包括在 require() 语句中——需要调用实用程序函数。他们会这样打电话:
module.exports = {
Init: function(pie) {
// does lots of other stuff, but now needs to round a number
// using the custom rounding fn provided in the common util code
console.log(util.Round(pie, 2)); // ReferenceError: util is not defined
}
};
实际运行的node.js 文件非常简单(嗯,对于这个例子)。它只是 require()'s 在代码中并启动自定义代码的 Init() fn,如下所示:
var util = require("./utilities.js");
var customCode = require("./programCode.js");
customCode.Init(Math.PI);
好吧,这不起作用,我收到来自 customCode 的“ReferenceError: util is not defined”。我知道每个所需文件中的所有内容都是“私有的”,这就是发生错误的原因,但我也知道保存实用程序代码对象的变量必须存储在某个地方,可能挂在 global 之外?
我搜索了global,但没有看到对utils 的任何引用。我正在考虑在自定义代码中使用 global.utils.Round 之类的东西。
所以问题是,鉴于实用程序代码可以被称为任何东西(var u、util 或实用程序),我到底该如何组织它以便其他代码模块可以看到这些实用程序?
【问题讨论】:
标签: javascript node.js