1

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

3
  • 1
    You'd have to do tradeData('TEST');. Or rewrite the module to module.exports = { pullData: pullData }; Commented Dec 8, 2017 at 9:51
  • 1
    The only problem with this second method is that the function is not hoisted Yes it is, it's not hoisted in the first method however. Commented Dec 8, 2017 at 10:06
  • Yeah sorry George, I meant it the other way round :) Commented Dec 9, 2017 at 2:55

2 Answers 2

1

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect answer! Not only helped my do it my way, but also showed me a few cool techniques :)
1

Try putting pullData in curly brackets:

module.exports = {pullData}

and when you require it, do this:

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

Hope it'll work.

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.