简体   繁体   中英

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: 主文件代码和控制台输出

导出文件中的代码

Try putting pullData in curly brackets:

module.exports = {pullData}

and when you require it, do this:

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

Hope it'll work.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM