1

This code tells me that the parse function is not a function:

const  MyModule = require('./MyModule.js');

MyModule.parse('...');

In my module script it's defined like this:

MyModule = {};

MyModule.parse = function(data){

};


module.exports.MyModule = MyModule;

What am I doing wrong?

1
  • Use exports.parse = function(data) {.... Or access the module via MyModule.MyModule.parse() Commented Jan 17, 2018 at 13:34

2 Answers 2

1

You have to understand that you are not exporting MyModule but an object (module.exports to be exact) with a member called MyModule (this is what you assigned to it).

If, in your code that requires MyModule, you console.log the result of your require, it will look like:

{ MyModule: {parse: [Function] } }

which is the module.exports object with a property (object) called MyModule that has a property (function) called parse.

So when you require you are getting the module.exports object that you assigned MyModule to and not just MyModule.

If you were to change your module.exports code to:

module.exports.X = MyModule;

Your code that required MyModule would then log:

{ X: {parse: [Function] } }

and you would call it as

MyModule.X.parse(...).

If you then changed your code to read

const MyFabulousModule = require('./MyModule'); 

you would then call it like:

MyFabulousModule.X.parse(...);

Finally, if you added another line to your module:

module.exports.Y = 4;

And then in your calling code added:

console.log(MyFabulouseModule.Y);

you would see the value 4 logged to the console.

Code:

MyModule.js

const MyModule = {};
MyModule.parse = function(data) {
    console.log(data);
};

module.exports.X = MyModule;
module.exports.Y = 4;

test.js

const MyModule = require("./MyModule");

console.log(MyModule);

MyModule.X.parse("hello world");

console.log(MyModule.Y);

To run: node test.js

Sign up to request clarification or add additional context in comments.

Comments

0

First of all, you need to add a keyword in definition object. const MyModule = {}; And you export the object, which you appoint to constant, so you need to call the object from it like this: MyModule.MyModule.parse('...')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.