I'm trying to split my node module functions into additional files as there are numerous functions I'm looking to add.
I would like to call the main file's functions into files loaded from lib and be able to call the lib functions directly, see:
In my main file 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;
Then in lib/catalog.js
function Catalog () {};
Catalog.prototype.getCategories = function () {
return Api.get('categories');
}
module.exports = Catalog;
Then I'm hoping to achieve the following when the module is required, so the Catalog file will give access to :
var Module = require('module');
api = new Module({
url: 'http://example.com', // without trailing slash
username: 'username',
password: 'password'
});
api.Catalog.getCategories();
When doing it this way I am getting the following error:
TypeError: Cannot read property 'getCategories' of undefined
Is there a recommended way to achieve this or perhaps splitting it down into multiple node modules?
Try adding require for the new modules
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.