如何在NodeJS中调用导出的函数?哪个可以嵌套?

时间:2018-08-27 12:26:45

标签: javascript node.js express mocha

这是我正在导出的app.js中的函数:

var app = {
  start: function() {
    //sample function
    exports.msgReceived = function() {
      return "Tomorrow 8pm near city hall";
    }
  }
}
module.exports = app;

我有一个名为messages.js的文件,我想在其中调用start函数以及msgReceived函数:

let subscriber = require('app');

it('server gets connected', function(done) {
  subscriber.start(); // working
  subscriber.msgReceived(); // not working
  done();
});

我该怎么做?

由于使用var关键字,我只能访问start函数。我的代码编辑器IntelliSense没有指向msgReceived函数。

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作,在运行start()之后在app对象上设置新功能。

var app = {
  start: function() {
    //sample function
    this.msgReceived = function() { // `this` refers to `app`
      return "Tomorrow 8pm near city hall";
    }
  }
}
module.exports = app;

如果您想使用智能感知功能,则可能必须包含

var app = {
  start : ...,
  msgReceived: null // or undefined... or anything.
}

答案 1 :(得分:0)

也许这可以帮助您

[init] this might take a minute or longer if the control plane images have to be pulled

var app = {
  start: function() {
    //sample function
    let msgReceived = function() {
      return "Tomorrow 8pm near city hall";
    };
    return {msgReceived: msgReceived};
  }
}
module.exports = app;