I'm getting the error while running the following code in Node.js
var assert = require('assert'); var request = require('request'); var index = require('./index'); it('verify javascript function', function(done) { var v2 = index.AddNumbers(5, 6); assert.equal(11, v2); done(); });
The index.js
file contain the following code:
function AddNumbers(a,b){ return a+b; }
What am I doing wrong?
The TypeError: "x" is not a function can be fixed using the following suggestions: Paying attention to detail in code and minimizing typos. Importing the correct and relevant script libraries used in code. Making sure the called property of an object is actually a function.
The TypeError object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type. A TypeError may be thrown when: an operand or argument passed to a function is incompatible with the type expected by that operator or function; or.
This is a standard JavaScript error when trying to call a function before it is defined. This error occurs if you try to execute a function that is not initialized or is not initialized correctly. This means that the expression did not return a function object.
A function is a relation in which each input has only one output. In the relation , y is a function of x, because for each input x (1, 2, 3, or 0), there is only one output y. x is not a function of y, because the input y = 3 has multiple outputs: x = 1 and x = 2.
This happened to me many times because of circular dependency, check if you have 2 classes that are requiring each other, remove one of them from requiring the other and the issue should be solved
With NodeJS modules, to make something public, you have to export it. Add this to the end of index.js
:
module.exports.AddNumbers = AddNumbers;
(That's using the old CommonJS modules. For ESM, it would be export AddNumbers;
)
Here it is running on my machine:
$ cat index.js function AddNumbers(a,b){ return a+b; } module.exports.AddNumbers = AddNumbers; $ cat example.js var index = require('./index'); var v2 = index.AddNumbers(5,6); console.log(v2); $ node example.js 11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With