Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

313
Views
Return value from externally called fs.Readfile() in node

I am trying to get a value returned from a function where I read and write a file using fs.readFile/writeFile in Node.

In my main server.js file, a request comes in and I then want to send an email from another file called sendEmail.js:

const fs = require('fs')
const sendMail = require('./sendEmail')

async function sendAnEmail() {
    let resultOfSend = await sendMail.sendEmail()
    resultOfSend.then((result)=>{
      // return the result
    }        
}

sendAnEmail();

In sendEmail I first read a file to get the email to send to, then write to a second file then, if all is good, I send an email (from a separate function):

async function sendEmail() {
    // Check if user exists
    fs.readFile('./file.json', (err, data) => {
        if(err) {
            throw error
        }
        else {
            let users = JSON.parse(data)
            let dataToWrite = JSON.stringify(users)

            fs.writeFile('./file2.json', dataToWrite, (err) => {
                if(err) {
                    console.error(err)
                    throw error
                }
                else {
                    return generateEmail(users)
                        .then((info) => {
                           return info
                        })
                        .catch(console.log('err'))
                }
            })
        }
    })
}

async function generateEmail(user) {
        let msgText = 'hello world'

        // Set the mail options
        const mailOptions = {
           ...
        }
        
        // Send the mail
    let info = await transporter.sendMail(mailOptions)
    return info
}

module.exports = {sendEmail}

What I can't get is a value for the resultOfSend variable. Keeps coming back undefined, I think because the promise hasn't yet been fulfilled.

How do I get a value to return from the sendEmail function back to the server.js file where it's called from?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You're using await and async in sendEmail but not returning any Promise (So the sendEmail function doesn't return anything and this is why you get undefined). Nevertheless, on the response you're trying to call .then() even though you used await.

So you should:

  1. return Promise in the sendEmail function.
  2. decide how you want to handle it, if you use async-await then dont use .then() and just analyze the variable and vice versa.
  3. generateEmail() function should also return Promise.

For example:

async function sendEmail() {
return new Promise((resolve, reject) => {
    // Check if user exists
    fs.readFile('./file.json', (err, data) => {
        if(err) {
            reject()
        }
        else {
            let users = JSON.parse(data)
            let dataToWrite = JSON.stringify(users)

            fs.writeFile('./file2.json', dataToWrite, (err) => {
                if(err) {
                    console.error(err)
                    reject()
                }
                else {
                    generateEmail(users)
                        .then((info) => {
                            resolve(info)
                        })
                        .catch(
                            console.log('err')
                            reject()
                        )
                }
            })
        }
    })
})
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!