0

I'm having trouble accessing the returned value of an imported module function in Node.

So, I have a simple function that returns a string. This is defined in a variable in my module code and exported:

var string = function() {
  console.log('ran');
  return 'string';
};

module.exports = string;

Then I require this in the usual way and assign to a variable. Finally, I console.log the variable, expecting 'ran' followed by 'string'.

var String = require('./string-module');

var stringInstance = new String();

console.log(stringInstance);

Instead, I get 'ran' (which I logged to check the function ran correctly / pathing was correct) followed by an empty object ({}) in my console.

I'm new to working with Node modules and I suspect I'm missing something regarding synchronous and asynchronous code.

Many thanks!

heydon
  • 315
  • 3
  • 9
  • 1
    Why you expect `"string"` ? this is how javascript work. BTW post title do not match your "issue", `undefined != {}` . If you don't use the `new` keyword you will have what you expect . see : http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – Hacketo Nov 16 '15 at 08:42
  • 1
    As it should... you did nothing to initialize the object. – Jeff Mercado Nov 16 '15 at 08:43
  • Okay, thanks. I guess I'm not used to using constructors. It began as a straight function call and should stay like that. No point adding properties to the prototype for something like this. – heydon Nov 16 '15 at 10:34

0 Answers0