Samurai Jack
Samurai Jack

Reputation: 3135

How to export a function from other file in NodeJS

I have two files:

myService.js

const Period= require('./period');
const myService = module.exports = {};

const defaults = {
    heating: new Period('heating', 'Oct', 15, 'Mar', 1),
    cooling: new Period('cooling', 'Apr', 15, 'Sep', 15)
};

const periods = {
    AustraliaDefault: {
        heating: new Period('heating', 'Jul', 1, 'Aug', 31), 
        cooling: new Period('cooling', 'Sep', 1, 'Mar', 1)
    }
};

myService.getPeriod = function (site, key) {
    return Promise.all([
        myService.findHeat(site, key),
        myService.findCool(site, key)
    ]).spread(function (heating, cooling) {
        return { heating: heating, cooling: cooling };
    });
};

myService.findHeat = function (site, key) {
    return Promise.resolve(periods[key] && periods[key]['heating'] || defaults['heating']);
};
myService.findingCoolingSeason = function (site, key) {
    return Promise.resolve(periods[key] && periods[key]['cooling'] || defaults['cooling']);
};

and Breakdown.js

...
const myService = require('./myService');
...

check('no use of heating during summer', function (report) {
    const model = report.findSection('Breakdown').model;
    const heatingSeries = _.findWhere(model.series, { name: 'Space heating' });
    if (!heatingSeries || model.series.length === 1) {
        return;
    }

    const totalAccounts = _.size(report.asModel().accountNumbers);
    const warnings = _.compact(_.map(['May', 'Jun'], function (monthLabel) {
        const summerIndex = _.indexOf(model.xAxis, monthLabel);
        const heatingSummerCost = heatingSeries.data[summerIndex];
        if (heatingSummerCost > (totalAccounts * maxSum)) {
            return {
                month: monthLabel,
                cost: heatingSummerCost,
                accounts: totalAccounts
            };
        }
    }));
    this.should(!warnings.length, util.format('breakdown chart indicates heating (%s) in summer (%s) in %d account(s)', _.pluck(warnings, 'cost'), _.pluck(warnings, 'month'), totalAccounts));
}),

The first file must describe the seasons(summer, winter) which are different between northern and southern hemisphere. I must call somehow myService in Breakdown . If it is let as default, it will detect that there is use of heating in summer (because in default in takes the northern hemisphere seasons) but it must be able to check for which one to compute it.

What I've tried is to import myService into Breakdown and instead of mapping ['May', 'Jun'] to use myService.findHeat or myService.Seasons and others but it doesn't work. It lets them as undefined no matter what method I use.

Any suggestions?

Upvotes: 0

Views: 572

Answers (2)

Kalana Demel
Kalana Demel

Reputation: 3266

If you haven't added the following line to myService.js if you haven't already.

exports.myService = myService

EDIT

try removing,

const myService = module.exports = {};

and adding,

exports.myService = myService

At the bottom.

Update

If you want to use it as a module try something like,

module.exports = {
  sayHelloInEnglish: function() {
    return "HELLO";
  },

  sayHelloInSpanish: function() {
    return "Hola";
  }
};

Upvotes: 3

Peter Grainger
Peter Grainger

Reputation: 5137

I believe your issue is the line

const myService = module.exports = {};

what you are doing here is the equivalent to

const myService = {};
module.exports = {};
myService.someFunction = function() {...}
console.dir(myService) // output {someFunction:function(){}}
console.dir(require('./my-service')) //output {}

So the module you are exporting will be an object with no attributes. You need to move the module.exports

const myService = {};

Then after all your code use

module.exports = myService;

In the context of your code

const Season = require('./season');
const myService = {};

const defaults = {
    heating: new Season('heating', 'October', 15, 'March', 1),
    cooling: new Season('cooling', 'April', 15, 'September', 15)
};

const seasons = {
    AustraliaDefault: {
        heating: new Season('heating', 'July', 1, 'August', 31), 
        cooling: new Season('cooling', 'September', 1, 'March', 1)
    }
};

myService.gettingSeasonalityAnalysis = function (site, cohortKey) {
    return Promise.all([
        myService.findingHeatingSeason(site, cohortKey),
        myService.findingCoolingSeason(site, cohortKey)
    ]).spread(function (heating, cooling) {
        return { heating: heating, cooling: cooling };
    });
};

myService.findingHeatingSeason = function (site, cohortKey) {
    return Promise.resolve(seasons[cohortKey] && seasons[cohortKey]['heating'] || defaults['heating']);
};
myService.findingCoolingSeason = function (site, cohortKey) {
    return Promise.resolve(seasons[cohortKey] && seasons[cohortKey]['cooling'] || defaults['cooling']);
};

module.exports = myService;

I created a glitch to show this working in an api: https://ubiquitous-seer.glitch.me/findingCoolingSeason

You can edit the code here to play around with it: https://glitch.com/edit/#!/join/e6f80fed-05b7-45de-8366-64fb2f13bd6d

Here is a read only view: https://glitch.com/edit/#!/ubiquitous-seer

You need to remember that you are using Promises so remember to use .then when calling the function

Upvotes: 3

Related Questions