Jigar Jain
Jigar Jain

Reputation: 1447

Function from require() throws undefined error

As a beginner to NodeJS this might be straigtforward but yet I am unable to figure out where I am going wrong

My home.js file is as follow

module.exports = function (deps) {
  var sample = require('../lib/sample'), // My own library
      express   = require('express'),
      router    = express.Router();

  router.get('/', function (req, res) {
     op = sample.parse('hi'); // Error here
     res.send(op);
  });

  return router;
 };

Under lib folder, my sample.js code is

module.exports = function () {

  function parse(text) {
      return 'hello' + text;
  }

  return {
      'sample': {
          'parse': parse
      }
  };
};

But I get an error saying undefined is not a function on the highlighted line. Can anyone let me know what I am missing?

Upvotes: 1

Views: 136

Answers (3)

Alex
Alex

Reputation: 11255

Change your exports to:

module.exports = function () {

  function parse(text) {
      return 'hello' + text;
  }

  return {
      'parse': parse
  };
};

Upvotes: 1

minuteman3
minuteman3

Reputation: 393

Your module.exports evaluates to a function which when called yields the object containing the parse function you are trying to call, under some nesting. You might try restructuring your sample.js file to look like this:

function parse(text) {
    return 'hello' + text;
}

module.exports = {
    parse: parse
};

Unless you really need the function wrapping shown in your example. In that case you'll have to unwrap it where you import it, so something like this:

var sample = require('../lib/sample')().sample

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239683

Since you export a function, sample will be a function now. You need to explicitly execute it to get the same object. So, you need to do something like this

var sample = require('../lib/sample')().sample

Now, the require statement returns the function, and we immediately execute it, which returns an object with sample property. Since you are interested in sample property only, we get only the sample property.

If you were planning to hide the implementation of parse from the users, I would suggest doing

function parse(text) {
    return 'hello' + text;
}

module.exports = {
  'parse': parse
};

Now, you are simply exporting the parse function, in an object and the code which requires this module will be able to use parse function, like you mentioned in the question.

Upvotes: 4

Related Questions