Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'TypeError: is not a function' in Node.js

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?

like image 389
Karthick Gk Avatar asked Nov 23 '15 06:11

Karthick Gk


People also ask

How do I fix TypeError is not a function?

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.

What is TypeError in node JS?

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.

Is not a function TypeError is not a function?

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.

What is not a function?

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.


2 Answers

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

like image 193
shimi_tap Avatar answered Sep 21 '22 13:09

shimi_tap


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 
like image 41
T.J. Crowder Avatar answered Sep 18 '22 13:09

T.J. Crowder