如何使用node-email-templates作为initialize / act风格对象?

(在那里开放给行话的build议)

我试图从节点控制台应用程序设置一个简单的电子邮件发件人。 看完这个答案后, node-email-templates看起来就像是要走的路。 但我不知道如何让这个库工作在一个“现在初始化,使用后”风格的对象。 示例代码不会这样做,它正在初始化对象并同时发送 。 节点邮件给出了我习惯的样式的一个很好的例子:

 var nodemailer = require("nodemailer"); // create reusable transport method (opens pool of SMTP connections) var smtpTransport = nodemailer.createTransport("SMTP",{ service: "Gmail", auth: { user: "gmail.user@gmail.com", pass: "userpass" } }); // setup e-mail data with unicode symbols var mailOptions = { from: "Fred Foo ✔ <foo@blurdybloop.com>", // sender address to: "bar@blurdybloop.com, baz@blurdybloop.com", // list of receivers subject: "Hello ✔", // Subject line text: "Hello world ✔", // plaintext body html: "<b>Hello world ✔</b>" // html body } // send mail with defined transport object smtpTransport.sendMail(mailOptions, function(error, response){ if(error){ console.log(error); }else{ console.log("Message sent: " + response.message); } // if you don't want to use this transport object anymore, // uncomment following line: // smtpTransport.close(); // shut down the connection pool, no more messages }); 

我真的很想做的事情是:

 // require node-email-templates // setup smtp transport, store it as a property of another object, // let's call it Alert // when an alert needs to send an email it will pick a template // name and tell node-email-templates to send that template, // with appropriate local variables 

这似乎并不罕见,但是如果我可以根据所提供的示例代码进行工作,那该死的。

在查看源代码并发现node-email-templates的主要条目是一个事件驱动的过程的结构之后,我怀疑你不需要付出很多努力就可以做到。

如果这样做不能阻止你,你可能会考虑从模块的main.js函数入口点创build渲染器和传输,并重构它以包含更多的参数来表示你需要的预先configuration的资源。

另一种可能的方法是在主入口函数中添加对外部定义的事件处理程序的调用,以设置对外部资源的引用。

应该指出的是,这些更改都会限制您更新现有模块而不会丢失修改的能力。

但是,在编写图书馆时,没有简单的方法可以将基本上是事件驱动的过程转换成线性的,程序化的过程,而不需要修改其来源。