NodeJS prototyping with module.exports - javascript

I've made a class in my NodeJS app and used module.exports along with a require() statement to bring it into my main server script:
// ./classes/clientCollection.js
module.exports = function ClientCollection() {
this.clients = [];
}
// ./server.js
var ClientCollection = require('./classes/clientCollection.js');
var clientCollection = new ClientCollection();
Now I'd like to add functions onto my class like so:
ClientCollection.prototype.addClient = function() {
console.log("test");
}
However when I do this I get the following error:
ReferenceError: ClientCollection is not defined
How do I properly add functions to a class using prototyping in a NodeJS app?

I think that you need.
function ClientCollection (test) {
this.test = test;
}
ClientCollection.prototype.addClient = function() {
console.log(this.test);
}
module.exports = ClientCollection;
or
function ClientCollection () {
}
ClientCollection.prototype = {
addClient : function(){
console.log("test");
}
}
module.exports = ClientCollection;

For various reasons, this structure:
module.exports = function ClientCollection() {
this.clients = [];
}
does not define the symbol ClientCollection outside of the function itself so you can't refer to it elsewhere in the module to add to the prototype. So, instead, you need to define it outside and then assign it to exports:
function ClientCollection() {
this.clients = [];
}
ClientCollection.prototype.addClient = function() {
// code here
}
module.exports = ClientCollection;

Related

Exporting multiple functions with arguments

All I am trying to do is to export two functions from a module. One function taking an argument and the other with no argument:
function initClass(params)
{
return new Promise( (resolve, reject) => {
if (!wallet) {
wallet = new WalletClient(params);
resolve(wallet);
} else {
console.log('Wallet is initialized');
resolve(wallet);
}
});
}
function getInstance()
{
return wallet;
}
For initClass(params) only, I can do this as:
module.exports = (params) => {
initClass(params)
}
And then I call this as:
var init = require('./class.js')(params).initClass(params);
This works fine.
Now, for me to export getInstance() as well, I have tried to do the following but it doesn't seem to work.
module.exports = (params) => {
initClass(params),
getInstance
}
This complaints that there is no function getInstance.
Then I tried this:
module.exports.init = (params) => {
initClass(params)
}
module.exports.instance = {
getInstance
}
Then call them as:
var init = require('./class.js').init(params).initClass(params);
What is the proper way to export multiple functions like this?
Thank you.
You're making it more complex than needed. Once you have your functions defined, you can export it with this:
module.exports = {
initClass,
getInstance
}
To use it, you do this:
const init = require("./class.js");
init.initClass(params);
const instance = init.getInstance();
What you're exporting from the module is an object (which I've named init in the example above) that contains two functions. You don't have to pass arguments to the functions at the time you require.
module.exports is basically an object with keys which can refer to any variables/functions of your file.In your case,
module.exports.initClass = function (params){
...
}
module.exports.getInstance = function (){
}
When importing it
var init = require('./class.') // init object has two keys -> initClass and getInstance
init.initClass('abc')
init.getInstance()
If i'm understanding correctly you are trying to export multiple methods if that is the case simple use this.
module.exports = {
method: function() {},
otherMethod: function(parmas) {}
}
In your code use like this.
var init = require('./class.js');
init.method()
init.otherMethond(paramObj)
If you want below scenario you need to check out about method chaining.
var init = require('./class.js').init(params).initClass(params);

How to access object.prototype methods from another file using module.exports?

If I want to use an object and its methods in another file, how would I set up my module.exports?
Object:
var Object = function ()
{
...
}
Object.prototype.foo = function (param)
{
...
}
Module.export:
module.exports = {
Object : Object
}
or
module.exports = {
Object : Object,
foo : Object.prototype.foo
}
?
A few ways of doing this but if you're trying to access prototype methods from your other file, then you'll need to instantiate your constructor,
something like:
For ex:
// lib.js
var YourThing = function () {
}
YourThing.prototype.someMethod = function () {
console.log('do something cool');
}
module.exports = YourThing;
// index.js
var YT = require('./lib.js');
var yourThing = new YT();
yourThing.someMethod();
module.exports = Object;
This will export your Object as a Module.
If your object is not renewed in your app, the best way to use it as an executed function with late binding of its prototype methods
const _ = require('lodash')
var Object = function ()
{
..
_.bindAll(this); // at last bind all methods. this way you won't miss a method
}
Object.prototype.foo = function (param)
{
...
}
module.exports = new Object();
then you can call the functions like,
const myObj = require('./object-file')
myObj.myMethod();
If you need reusable component,
module.exports = Object;
const _obj = require('./object-file'); // you can call this way anywhere in any function and for every require, it creates a new object.
var object = new _obj();
_obj.anyMethod();

how to implement factory design pattern in node js

I have a app.js file as below.
I am getting an error DesignFactory is not defined,
var fs = require('fs');
var dotenv = require('dotenv');
dotenv.load();
var designtokenfile = require ('./designtokenfile');
var designtokendb = require ('./designtokendb');
DesignFactory.storeDesign = function(type) {
if (type == 'file') {
return designtokenfile;
}
else if (type == 'db')
{
return designtokendb;
}
};
module.exports.DesignFactory = DesignFactory;
Since am new to nodejs environment I dont know how to write it. Please help me
From what I see you don't declare DesignFactory at any point. Start by declaring it's constructor.
// Constructor ES5
var DesignFactory = function() { ... }
// Prototype methods (must instantiate class to use these)
DesignFactory.prototype = {
storeDesign: function(type) {
// Code here
}
}
// Or you can use the static approach as in your code
DesignFactory.storeDesign = function(type) { ... }
Alternatively, you can use a standard object.
var DesignFactory = {};
DesignFactory.storeDesign = function(type) {
// Code here
};
you should declare the DesignFactory as a object before define property storeDesign.
file1.js
var fs = require('fs');
var dotenv = require('dotenv');
dotenv.load();
var designtokenfile = require ('./designtokenfile');
var designtokendb = require ('./designtokendb');
// declare the DesignFactory variable as a plain object.
var DesignFactory = {};
DesignFactory.storeDesign = function(type) {
if (type == 'file') {
return designtokenfile;
} else if (type == 'db') {
return designtokendb;
}
};
module.exports.DesignFactory = DesignFactory;
usage in file2.js
var DesignFactory = require('./file1');
DesignFactory.storeDesign(/*arguments*/);
Note:
Like the David Barker's answer, if you mean the DesignFactory is like a class in JAVA, you should define it as a Function.
function DesignFactory() {};

miss prototype functions when "new" a instance

I write a module in nodejs ,which Test.js ,code blow
function Test() {
this.key = 'value';
}
Test.prototype.foo = function () { return 'foo'; }
module.exports = Test;
and then, in B.js
var Test = require('./services/Test');
var test = new Test();
console.log(test.foo());
unfortunetly, I got "undefined method foo",
anyone who can Tell me what happended? thanks so much
Check your file location it should be in services directory.
function Test() {
this.key = 'value';
}
Test.prototype.foo = function () { return 'foo'; }
module.exports = new Test();//Test;
var test = require('./services/Test');
console.log(test.foo());
You can export the new object of Test class. try this.
Or you can use ES6 JavaScript that great.
In Test.js try moving the module.exports to before you define the prototype functions.
As below:
function Test() {
this.key = 'value';
}
module.exports = Test;
Test.prototype.foo = function () { return 'foo'; }

What is the best way to deal with this Namespace JavaScript Structure?

i have an object as namespace with three main-objects. I call this object one time and after this it is working for itself.
My Code is structured like this:
var Application = Application || {};
Application.Module1 = {
//Code with some functions
}
Application.Module2 = {
//Code with some functions
}
Application.Module3 = {
//Code with some functions
}
(function(){
Application.Module1.Start();
})();
Primarily the modules working among themselves. I would like to call for example when i'm in Module1 a function in Module2 like:
Module2.randomFunction();
and not:
Application.Module2.randomFunction();
But i think it is a bad idea to go
Application.Module1.Start.call(Application)
because i'm using also other objects like jQuery.
What do you think would be the right way?
You can use a pattern like this -
var Application = (function() {
var Module1 = {
function1 : function() {
console.log("function1");
Module2.function2();
}
};
var Module2 = {
function2 : function() {
console.log("function2");
}
};
var Module3 = {
function3 : function() {
console.log("function3");
}
};
return {
Module1: Module1,
Module2: Module2,
Module3: Module3
}
})();
Application.Module1.function1();

Categories