最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

从在节点JS另一个模块导入功能

运维笔记admin20浏览0评论

从在节点JS另一个模块导入功能

从在节点JS另一个模块导入功能

从某个文件夹来一直需要模块,此功能不起作用导入某些功能。

我使用nodemailer用于发送电子邮件。我有一个模块3个不同的文件夹中。问题是,进口(要求)电子邮件从另一个发送功能,以当前模块。它成为undefined和错误是myFunc is not a function。我做这样需要与index.js其中包括所需功能从文件夹功能非常简单的事情。但是,当我尝试使用它,它是不确定的。

服务/ mailTransport.js

const nodemailer = require('nodemailer');

const mailTransporter = nodemailer.createTransport({
    host: 'smtp.gmail',
    port: 587,
     secure: false, 
    auth: {
      user: '[email protected]',
      pass: 'myPassword'
    }
});

module.exports = mailTransporter;

服务/ index.js

const mailTransporter = require("./mailTransporter");
module.exports = { mailTransporter }

utils的/ mailTemplate.js

const { mailTransporter } = require("../services");

const sendEmail = function (obj, msg) {
return new Promise( (res, rej) => {
    let mailOptions = {
        from: '[email protected]',
        to: `${obj.to}`,
        subject: `${obj.subject}`,
        text: "plain text",
        html: "<b>" + msg + "</b>"
    };
    mailTransporter.sendMail(mailOptions, (error, info) => {
        mailTransporter.close();
        if (error) {
            rej(error);
        }
    console.log('Message sent: %s', info.messageId);
    res(info.messageId);
    });
})
}

module.exports = { sendEmail };

最后我要在项目/ emails.js在这里使用它

const { sendEmail } = require("../utils/mailTemplate");
const { vendorNotificationMessage } = require("../utils/emailMessages");

async function notifyVendors(steps) {
try {
    for(let step of steps) {
        if(step.vendor) {
            const message = vendorNotificationMessage(step);
            step.to = step.vendor.email;
            step.subject = "Step cancelling notification!";
            await sendEmail(step, message);
        }
    }
} catch(err) {
    console.log(err);
    console.log("Error in notifyVendors");
}
}

module.exports = { notifyVendors };

我预计,电子邮件将使用sendEmail功能来发送。但是,停止与错误TypeError: sendEmail is not a function

回答如下:

从一个模块导出一些正确的语法是

exports.globalObjectName = localObjectName

因此,在您第一个文件的导出语句应该是这样的

exports.mailTransporter = mailTransporter
发布评论

评论列表(0)

  1. 暂无评论