如何将节点模块拆分为其他文件?

时间:2015-11-26 13:33:30

标签: javascript node.js

我试图将节点模块功能拆分为其他文件,因为我想要添加许多功能。

我想将主文件的函数调用到从lib加载的文件中,并且能够直接调用lib函数,参见:

在我的主文件index.js中:

function Api(opt) {
  // set options
}

Api.prototype.get = function (endpoint) {
  return this.request('GET', endpoint, null);
};

Api.prototype.Catalog = require('./lib/catalog.js');

module.exports = Api;

然后在lib/catalog.js

function Catalog () {};

Catalog.prototype.getCategories = function () {
    return Api.get('categories');
}

module.exports = Catalog;

然后我希望在需要模块时实现以下功能,因此目录文件将提供以下访问权限:

var Module = require('module');

api = new Module({
    url: 'http://example.com', // without trailing slash
    username: 'username',
    password: 'password'
});

api.Catalog.getCategories();

当这样做时,我收到以下错误:

TypeError: Cannot read property 'getCategories' of undefined

是否有推荐的方法来实现这一目标,或者可能将其拆分为多个节点模块?

1 个答案:

答案 0 :(得分:0)

尝试为新模块添加require

var Module = require('module');
var Catalog = require('Catalog');
var Api = require('Api');

api = new Module({
    url: 'http://example.com', // without trailing slash
    username: 'username',
    password: 'password'
});

api.Catalog.getCategories();