nodemailer是否阻止fs.writeFile工作

83qze16e  于 2023-02-15  发布在  Node.js
关注(0)|答案(1)|浏览(123)

我尝试将表单数据写入一个json数据库文件,同时也使用nodeMailer在writeFile之前或之后执行,问题是,在我的代码中,只有writeFile看起来在执行,而nodeMailer没有执行,但是,如果我省略文件Write,nodeMailer就会执行,我就可以发送电子邮件。有谁能就如何运行这两个任务提供建议吗?

const messageDB = {
    messages: require('../models/messageDB.json'),
    setMessage: function (data) {
        this.messages = data
    }
}

const { body, validationResult } = require('express-validator')
const fs = require('fs')
const path = require('path')
const nodemailer = require('nodemailer')

exports.message_controller_get = (req, res, next) => {
    res.render('index')
}

exports.message_controller_post = [
  body('name', 'Full names must be specified').isLength({ min: 2, max: 40 }).trim(),
  body('email', 'Email address must be specified').isEmail().isLength({ min: 3, max: 40 }),
  body('msg', 'Message must be specified').isLength({ min: 20, max: 1000 }),

  (req, res, next) => {

    const errors = validationResult(req)

    if (!errors.isEmpty()) {
        
        console.log('there are errors: ' +  errors.array())
        return
    }
    const message = {
        name: req.body.name,
        email: req.body.email,
        msg: req.body.msg
    }
    const transporter = nodemailer.createTransport({
        host: 'smtp.ethereal.email',
        port: 587,
        auth: {
            user: 'lila.greenfelder71@ethereal.email',
            pass: 'DQnhbPkHBRzPU1UkAt'
        }
    });

    const mailOption = {
        from: 'Fred Foo 👻" <fred@homexclusiv.com>',
        to: 'payiyke@gmail.com',
        subject: `Message from ${req.body.email}:`,
        text: req.body.msg
    }
    
  
    messageDB.setMessage([...messageDB.messages, message])
    fs.writeFile(
        path.join(__dirname, '..', 'models', 'messageDB.json'),
        JSON.stringify(messageDB.messages),
        (err) => {
            if (err){
                return res.send(err)
            } else {
                transporter.sendMail(mailOption, (error, info) => {
                    if (error) {
                        console.log(error);
                        res.send('error')
                    } else {
                        console.log('Email sent :' + info.response)
                        res.send('success')
                    }
                })
               /*  return res.send('success') */
            }
            
        }
    )

    /* console.log(`${message.name}\t${message.email}`) */

    
    
  }
  
]

不用担心,密码是临时的

6kkfgxo0

6kkfgxo01#

很可能是writeFile方法在nodemailer代码块执行之前完成。您可以尝试将nodemailer代码块放在一个单独的函数中,并在writeFile方法完成后调用它。这样,writeFile方法将首先执行,然后调用sendEmail函数。sendEmail函数将随后执行nodemailer代码块以发送电子邮件。您可以尝试类似以下操作

const messageDB = {
    messages: require('../models/messageDB.json'),
    setMessage: function (data) {
        this.messages = data
    }
}

const { body, validationResult } = require('express-validator')
const fs = require('fs')
const path = require('path')
const nodemailer = require('nodemailer')

exports.message_controller_get = (req, res, next) => {
    res.render('index')
}

exports.message_controller_post = [
  body('name', 'Full names must be specified').isLength({ min: 2, max: 40 }).trim(),
  body('email', 'Email address must be specified').isEmail().isLength({ min: 3, max: 40 }),
  body('msg', 'Message must be specified').isLength({ min: 20, max: 1000 }),

  (req, res, next) => {

    const errors = validationResult(req)

    if (!errors.isEmpty()) {
        
        console.log('there are errors: ' +  errors.array())
        return
    }
    const message = {
        name: req.body.name,
        email: req.body.email,
        msg: req.body.msg
    }
    const transporter = nodemailer.createTransport({
        host: 'smtp.ethereal.email',
        port: 587,
        auth: {
            user: 'lila.greenfelder71@ethereal.email',
            pass: 'DQnhbPkHBRzPU1UkAt'
        }
    });

    const mailOption = {
        from: 'Fred Foo 👻" <fred@homexclusiv.com>',
        to: 'payiyke@gmail.com',
        subject: `Message from ${req.body.email}:`,
        text: req.body.msg
    }
    
  
    messageDB.setMessage([...messageDB.messages, message])
    fs.writeFile(
        path.join(__dirname, '..', 'models', 'messageDB.json'),
        JSON.stringify(messageDB.messages),
        (err) => {
            if (err){
                return res.send(err)
            } else {
                sendEmail(transporter, mailOption, res);
            }
        }
    )

    /* console.log(`${message.name}\t${message.email}`) */
    
  }
]

function sendEmail(transporter, mailOption, res) {
    transporter.sendMail(mailOption, (error, info) => {
        if (error) {
            console.log(error);
            res.send('error')
        } else {
            console.log('Email sent :' + info.response)
            res.send('success')
        }
    })
}

相关问题