squareArea is not a function when requiring module - javascript

I made a set of functions and none of them is working. Here's one of them, for example:
function squareArea(side) {
var sArea = side * side;
return sArea;
}
And this is how I require the module:
var mfs = require("m-p-formulas-js");
var test = mfs.squareArea(2);
console.log(test)
It returns this error:
TypeError: mfs.squareArea is not a function
What should I do to solve this?

You aren't exporting the function so it doesn't exist on the required module object. Assuming you're using ES5, use module.exports which contains the module's exports:
function squareArea(side) {
var sArea = side * side;
return sArea;
}
module.exports = {
squareArea: squareArea
};
You could also shorten it to this using the exports shortcut:
exports.squareArea = squareArea;

You need to export the function to make it available to others. Add the following to the bottom of your definition of m-p-formulas-js module:
module.exports = {
squareArea
}

Related

singleton pattern - require(...) is not a function

I've set up a class with a singleton design like this.
The file is called helpers.js.
class Helpers {
//Code
}
let singleton;
/**
* #returns {Helpers}
*/
const getHelpers = (options) => {
if (!singleton) {
singleton = new Helpers(options);
}
return singleton;
};
module.exports = getHelpers;
That means the first time, I'll have to do
const helpers = require('./helpers')(options);
And every time after, I just have to do:
const helpers = require('./helpers')();
For some reason I keep getting
TypeError: require(...) is not a function
My require requires the right file, and my VSCode autocorrect says that requiring it will give me a function that returns a Helpers, and that require(''')() will return a Helpers.
I have no idea what can be wrong.
EDIT
When I inspect the return value of require('./helpers') it's an object with some basic functions.

How to make a custom CasperJS module with custom parameter?

FileUtil.js:
exports.a = function(pre) {
var module = {}
module.writeStringToFile = function writeStringToFile() {
casper.log(pre + " succ");
};
return module
}
main.js:
var casper = require('casper').create();
var FileUtil = require('FileUtil').a('xxx')
FileUtil.writeStringToFile() //xxx succ
That works, but what I want is var FileUtil = require('FileUtil')('xxx') instead of require('FileUtil').a('xxx').
I tried exports = function(pre) ..., but it doesn't works.
So, how to make a custom CasperJS module with custom parameter?
If you want var FileUtil = require('FileUtil')('xxx') to be your object then you need to use module.exports. It can export a single object, which can even be a function:
module.exports = function(pre) {
var module = {}
module.writeStringToFile = function writeStringToFile() {
casper.log(pre + " succ");
};
return module
}
Of course, it would be a better form to rename the inner module variable to something else.

Execute NodeJS module with specific variables injected

I have a module like below
'use strict';
var val = GlobalVariable.someMethod();
...
...
module.exports = myExportedClass;
I am calling it with require('./myModule');. But would like to know if GlobalVariable can be dynamically injected.
I have tried this method, though I know that this does not work :)
(function(GlobalVariable) {
require('./myModule');
})(SomeOtherGlobalVariable);
So it did not, because module will execute in different scope. Is there any other way where I can pass my own version of GlobalVariable when using require.
Yes, it can be injected. Do something like the following:
module.exports = function(injectedObject) {
return {
doSomething: function() {
return injectedObject.something();
}
}
};
you can pass you variable as an argument when requiring it
yourvariable="value";
var file = require('./myModule')(yourvariable);
or can pass it separately, as file now contain function reference of module.exports
yourvariable="value";
var file = require('./myModule');
file(yourvariable)
your module will look like as:
module.exports = function(yourVaraible) {
yourVaraible.myfunction = function() {
};
return yourvariable;
};

Node.js double call to require()

//lib.js
var opt = 0
exports.set = function(arg) {
opt = arg
}
exports.prn = function() {
console.log(opt)
}
///prog.js
var lib = require('./lib')
var lib2 = require('./lib')
lib.set(222)
lib2.set(333)
lib.prn()
lib2.prn()
prog.js will output:
333
333
but I need it to output:
222
333
In ohter words, opt must be unique to variable lib and to variable lib2. How to achieve that?
That's because normally nodejs caches its modules which are got via require. You may use the following helper:
// RequireUncached.js
module.exports = function(module) {
delete require.cache[require.resolve(module)]
return require(module);
}
and the usage of the helper:
var requireUncached = require('RequireUncached.js');
requireUncached("./lib");
Have in mind that this approach is considered as bad practice and should not be used. I'll suggest to wrap your logic into a function, require the module and call the function. So, every time you get a new instance.
require will not load scripts multiple times, but always yield the same instance.
If you need different environments, make your module a constructor function that allows to be instantiated multiple times. Store opt on each object for that instead of in the (global) module scope.
// lib.js
module.exports = function constr() {
var opt = 0
this.set = function(arg) {
opt = arg
};
this.print = function() {
console.log(opt)
};
};
// prog.js
var lib = require('./lib'),
inst1 = new lib(),
inst2 = new lib();
/* or short:
var inst1 = new require('./lib')(),
inst2 = new require('./lib')(); */
inst1.set(222)
inst2.set(333)
inst1.print()
inst2.print()
The way the NodeJS module system works, the output is correct and your expectations contradict the design principle here.
Each module is loaded once and only once, and subsequent calls to require simply return the reference to the pre-existing module.
Maybe what you need to do is create a class you can create one or more instances of instead of using module-level globals.
Adding to Bergi's answer, You may also try it like
// prog.js
var lib = require('./lib')(),
lib2 = require('./lib')();
lib.set(222)
lib2.set(333)
lib.print()
lib2.print()
// lib.js
module.exports = function constr() {
var opt = 0
return { set : function(arg) {
opt = arg
},
print : function() {
console.log(opt)
}
}
};
Add this line as first line of your lib.js
delete require.cache[__filename]
now your module becomes in a separate namespace each time you require it.

Express.JS not recognizing required js file's functions

Even though, I've imported the JS file that includes the function that I will use, Node.JS says that it is undefined.
require('./game_core.js');
Users/dasdasd/Developer/optionalassignment/games.js:28
thegame.gamecore = new game_core( thegame );
^
ReferenceError: game_core is not defined
Do you have any idea what's wrong? Game_core includes the function:
var game_core = function(game_instance){....};
Add to the end of game_core.js:
module.exports = {
game_core : game_core
}
to games.js:
var game_core = require('./game_core').game_core(game_istance);
Requiring a module in Node doesn't add its contents to the global scope. Every module is wrapped in its own scope, so you have to export public names:
// game_core.js
module.exports = function (game_instance){...};
Then keep a reference in your main script to the exported object:
var game_core = require('./game_core.js');
...
thegame.gamecore = new game_core( thegame );
You can read more about it in the docs: http://nodejs.org/api/modules.html#modules_modules
An alternative approach:
if( 'undefined' != typeof global ) {
module.exports = global.game_core = game_core;
}

Categories

Resources