从在节点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