Send email after the upload is complete?

0

I have the following function for sending emails using the nodemailer and a HapiJS server:

let data = request.payload;
    if (data.file) {
        let name = data.file.hapi.filename;
        let caminho = __dirname + "/uploads/" + name;
        let file = fs.createWriteStream(caminho);

        file.on('error', function (err) {
            console.error(err)
        });

        data.file.pipe(file);

        data.file.on('end', function (err) {
            mailOptios.attachments.push({
                filename: name,
                path: caminho //push nos anexos quando o upload está concluido
            });
            reply('Upload Concluído');
        });
    }


    let destinatario = '[email protected]';
    let ass = 'teste com anexo';
    let email = 'Teste com anexo';
    let mailOptios = {
        from: usuario, //usuário está definido mais acima no código
        to: destinatario, //não incluí usuário aqui por questões de privacidade
        subject: ass,
        text: email,
        attachments: [
        ]
    };

    console.log(mailOptios);
    transporter.sendMail(mailOptios, function (err, info) {
        if (err){
            console.log(err)
        } else {
            console.log('Enviado! ' + info.response);
            return reply.response('Enviou')
        }
    })

However, the process is occurring asynchronously and the email is being sent before the full attachment upload occurs.

How do you leave this function synchronous or make sure the attachment is ready before sending the email?

    
asked by anonymous 01.09.2017 / 16:35

1 answer

1

You have to put all this code here:

let destinatario = '[email protected]';
let ass = 'teste com anexo';
let email = 'Teste com anexo';
let mailOptios = {
    from: usuario, //usuário está definido mais acima no código
    to: destinatario, //não incluí usuário aqui por questões de privacidade
    subject: ass,
    text: email,
    attachments: [
    ]
};

console.log(mailOptios);
transporter.sendMail(mailOptios, function (err, info) {
    if (err){
        console.log(err)
    } else {
        console.log('Enviado! ' + info.response);
        return reply.response('Enviou')
    }
})

Within data.file.on('end') , this is because on is an event, so it is sending a message that the upload is finished. I advise you to turn it all into a sendMail function and send the necessary parameters within the end

    
01.09.2017 / 18:42