繁体   English   中英

NodeJS-如何从另一个require()文件引用一个require()文件中的函数?

[英]NodeJS - How to reference function in one require() file from another require() file?

这是我第二个周末与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(),并启动了自定义代码的Init()fn,如下所示:

var util = require("./utilities.js");
var customCode = require("./programCode.js");

customCode.Init(Math.PI);

好吧,这行不通,我收到来自customCode的“ ReferenceError:util未定义”。 我知道每个必需文件中的所有内容都是“私有”的,这就是为什么会发生错误,但是我也知道,保存实用程序对象的变量将GOT存储在某个地方,也许与global

我搜索了global但是在那里没有看到对utils引用。 我当时正在考虑在自定义代码中使用诸如global.utils.Round之类的东西。

因此,问题是,考虑到实用程序代码实际上可以被称为任何东西(var u,util或utility),我该如何组织它,以便其他代码模块可以看到这些实用程序?

至少有两种方法可以解决此问题:

  1. 如果您需要文件中另一个模块的内容,则只需要它即可。 那很容易。
  2. 提供一些实际为您构建模块的东西。 我将在稍后解释。

但是,由于node.js模块系统不提供全局变量(如您期望的其他语言那样),因此您当前的方法不起作用。 除了使用module.exports导出的东西之外,您从所需的模块中什么都没有得到,并且所需的模块对需求者的环境一无所知。

require

为避免上述差距,您需要事先需要其他模块:

// -- file: ./programCode.js
var util = require(...);

module.exports = {
    Init: function(pie) {
        console.log(util.Round(pie, 2));
    }
};

require s已缓存,因此此时不要对性能进行过多考虑。

保持灵活性

在这种情况下,您不会直接导出模块的内容。 相反,您提供了一个将创建实际内容的构造函数 这使您能够提供一些其他参数,例如实用程序库的另一个版本:

// -- file: ./programCode.js
module.exports = {
    create: function(util){
      return {
        Init: function(pie) {
          console.log(util.Round(pie, 2));
        }
      }
    }        
};

// --- other file

var util     = require(...);
var myModule = require('./module').create(util);

如您所见,这将在您调用create时创建一个对象。 这样,作为第一种方法,它将消耗更多的内存。 因此,我建议您只require()

暂无
暂无

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

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