如何从NodeJS中的其他文件导出函数

时间:2017-04-18 08:38:07

标签: javascript node.js

我有两个文件:

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']);
};

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));
}),

第一个文件必须描述北半球和南半球之间不同的季节(夏季,冬季)。 我必须在细分中以某种方式调用 myService 。如果它是默认设置,它将检测到夏季有加热使用(因为默认情况下是在北半球季节)但它必须能够检查哪一个计算它。

我尝试过将myService导入细分,而不是将['May', 'Jun']映射到使用myService.findHeatmyService.Seasons和其他人,但它不起作用。无论我使用什么方法,它都可以undefined

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

如果您还没有将以下行添加到myService.js中。

exports.myService = myService

修改

尝试删除,

const myService = module.exports = {};

并添加,

exports.myService = myService

在底部。

更新

如果您想将其用作模块,请尝试使用

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

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

答案 1 :(得分:3)

我相信你的问题就在这一行

const myService = module.exports = {};

你在这里做的是等同于

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

因此,您导出的模块将是没有属性的对象。您需要移动module.exports

const myService = {};

然后在你的所有代码之后使用

module.exports = myService;

在您的代码的上下文中

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;

我创建了一个小故障,以显示这在api中工作: https://ubiquitous-seer.glitch.me/findingCoolingSeason

您可以在此编辑代码以使用它: https://glitch.com/edit/#!/join/e6f80fed-05b7-45de-8366-64fb2f13bd6d

这是一个只读视图: https://glitch.com/edit/#!/ubiquitous-seer

你需要记住你正在使用Promises,所以记得在调用函数时使用.then