Oliver Chalk
Oliver Chalk

Reputation: 177

Node.js issues with exporting functions

I have a few questions about the nature of exporting functions in NodeJS:

Firstly this is an acceptable way to export a function:

exports.bread = function bread() {
  return 'bread: 2';
};

However, it is not possible (maybe?) to export a function using this method:

function pullData(pair) {
  console.log(pair);
}

module.exports = pullData;

The only problem with this second method is that the function is not hoisted and limits its' use elsewhere?

Another method for exporting variables is to include the variables within an object and export that object. However, in this case, the functions within the module have a limited scope...

So is there any easy way to export declarative functions and use them, or is doing so not something I should strive to achieve?

Screenshots from project: Main file code and console output

Code from the exporting file

Upvotes: 1

Views: 207

Answers (2)

cdimitroulas
cdimitroulas

Reputation: 2549

When you write module.exports = something you are exporting only one thing. So your code should look like this

var pullData = require('./getTicker')
pullData('TEST')

If you want to write it the way you have done so then you need to export it differently, as only part of the module.exports object. You can do this by writing exports.pullData = pullData in your getTicker file.

Then you can import it and use it like you did:

var trackData = require('./getTicker')
trackData.pullData('TEST')

Upvotes: 1

user9071872
user9071872

Reputation:

Try putting pullData in curly brackets:

module.exports = {pullData}

and when you require it, do this:

const {pullData} = require("./getTicker");

Hope it'll work.

Upvotes: 1

Related Questions