【问题标题】:How to make node.js function run without visiting port如何让node.js函数在不访问端口的情况下运行
【发布时间】:2021-04-28 18:48:56
【问题描述】:

这可能是一个完全愚蠢的问题,但我有一个非常简单的 node.js 测试应用程序,它每 3 分钟发送一封电子邮件(毫无意义,但仅用于学习目的)。该应用程序有效,但只有在我访问端口:3000 时才能运行 - 我明白为什么,因为那是侦听器所在的位置,但我如何在不必访问端口的情况下执行电子邮件代码?还是我误解了它的工作原理?下面的代码 - 感谢任何帮助????

const http = require('http');
const nodemailer = require('nodemailer');

let app = http.createServer((req, res) => {
    const init = async () => {

        const email = async () => {
    
            let transport = nodemailer.createTransport({
                host: "smtp.mailtrap.io",
                port: 2525,
                auth: {
                  user: "user",
                  pass: "pass"
                }
              });
            
            const message = {
                from: 'nodeapp.test.com', // Sender address
                to: 'to@email.com',         // List of recipients
                subject: 'Test Email', // Subject line
                text: 'Testing testing 123' // Plain text body
            };
        
            let info = await transport.sendMail(message, function(err, email) {
                if (err) {
                  console.log(err)
                } else {
                  console.log(email);
                }
            });
    
        }
    
    
        email()
        setInterval(email, 180000)
    }  
    init()
})

app.listen(process.env.PORT || 3000, () => {
    console.log('Server running at http://127.0.0.1:3000/')
})

【问题讨论】:

    标签: node.js port nodemailer


    【解决方案1】:

    当然,其中一种实用的方法是使用Cron。 为此,只需首先安装该软件包:“npm i cron”。 创建一些“index.js”(内容如下)并运行“node index.js”:

    const CronJob = require('cron').CronJob;
    const nodemailer = require('nodemailer');
    
    const runSendEmail = async () => {
        // HERE YOU CAN IMPLEMENT WHAT YOU WANT (I just kept your code the same)
        // for example you can test this only with logging something like this
        // console.log(new Date());
        // and after that you can implement your functionality here
        // or you can separate the function logic in different file
    
        let transport = nodemailer.createTransport({
            host: "smtp.mailtrap.io",
            port: 2525,
            auth: {
                user: "user",
                pass: "pass"
            }
        });
    
        const message = {
            from: 'nodeapp.test.com', // Sender address
            to: 'to@email.com',         // List of recipients
            subject: 'Test Email', // Subject line
            text: 'Testing testing 123' // Plain text body
        };
    
        let info = await transport.sendMail(message, function(err, email) {
            if (err) {
                console.log(err);
            } else {
                console.log(email);
            }
        });
    }
    
    class Cron {
        static async start() {
            await new CronJob(
                '*/3 * * * *', // cron time period (At every 3rd minute)
                () => { // RUNNING FUNCTION
                    try {
                        runSendEmail();
    
                        // you can also get the result of "runSendEmail" function
                        // for that you need to return the value from "runSendEmail"
                        // and may you'll need to do that with async/await like this:
                        // const result = await runSendEmail();
                        // also in this case don't forget to add "async" before RUNNING FUNCTION's parentheses
                    } catch (err) {
                        console.log(err.message); // or   throw Error(err.message);
                    }
                },
                null,
                true
            );
        }
    }
    
    Cron.start();
    

    【讨论】:

    • 太棒了,非常感谢您的帮助??‍♂️
    猜你喜欢
    • 2021-11-05
    • 1970-01-01
    • 2021-12-28
    • 2013-12-31
    • 1970-01-01
    • 2022-07-05
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多