如何在不访问端口的情况下使 node.js 函数 运行

How to make node.js function run without visiting port

这可能是一个完全愚蠢的问题,但我有一个非常简单的 node.js 测试应用程序,它每 3 分钟发送一封电子邮件(毫无意义,但仅用于学习目的)。该应用程序可以运行,但只有在我访问 port: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/')
})

当然可以,其中一种实用的方法是使用 Cron。 为此,首先安装该软件包:“npm i cron”。 创建一些“index.js”(内容如下)和运行“节点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();