如何在node.js中导出模块

时间:2014-12-17 19:17:46

标签: javascript node.js

emailConfirmation.js:

var configAuth = require('../../authentication/sendgrid');
var sendgrid = require('sendgrid')(configAuth.sg.username, configAuth.sg.password);

var from_address = "mycompany@pubcrawlsp.com";
var text_body = "sometextbody";
var html_body = "somehtml";

我需要在我的路线中导出,以便在后期路线中使用,如下所示:

app.post('/', function(req, res) {

     sendgrid.send({
        to:         req.body.email,
        from:       the from_adrres variable from the other file,
        subject:    "Some subjec",
        text:       the text_body variable from the other file
        html:       the html_body variable from the other file
    }, function(err, json) {
        if (err) {
            return console.error(err);
        }
        console.log(json);
});


});

如何导出emailConfirmation.js并使用类似的?

1 个答案:

答案 0 :(得分:0)

首先为您的代码创建一个文件。

在文件的末尾,你会"暴露"部分代码给消费者。例如:

在你的情况下,你可以像这样包装你的代码:

module.exports.set = function(app) {
  app.post('/', function(req, res) { 
      /* the post code goes here */ 
  });
};

你可以在app.js上使用app.js来消费它:

require('./sendgrid').set(app);

这将有效地设置sendgrid的路由。