How do I get it to conosle.log the "Read It" before the "Ex It"?

Issue

app.get('/', async (req, res) => {
    await fs.readFile('./views/website/index.html', 'utf8', (err, d) => {
        data = d
        console.log("Read It")
            // console.log(data)
    });

    console.log("Ex It")
    res.render('website/index', { 'data': data });
});

I tried to use the async function and await, but when I run it, it is console logging the "Ex It" before the "Read It". How do it get it to output the "Read It" before the "Ex It"?

Solution

you can use the promises version as suggested by the comments "require('fs').promises"

app.get('/', async (req, res) => {
  data = await fs.promises.readFile('./views/website/index.html', 'utf8');
  console.log("Read It")
  console.log("Ex It")
  res.render('website/index', { 'data': data });
});

or just put everything in the callback

app.get('/', async (req, res) => {
  fs.readFile('./views/website/index.html', 'utf8', (err, d) => {
      data = d
      console.log("Read It")
      console.log("Ex It")
      res.render('website/index', { 'data': data });
  });
});

or you could wrap the callback in a promise

app.get('/', async (req, res) => {
  await new Promise((resolve, reject) => {
    fs.readFile('./views/website/index.html', 'utf8', (err, d) => {
      data = d
      console.log("Read It")
      resolve();
    });
  });

  console.log("Ex It")
  res.render('website/index', { 'data': data });
});

or use the synchronous version (actually don’t do this)

app.get('/', async (req, res) => {
  data = fs.readFileSync('./views/website/index.html', 'utf8');
  console.log("Read It")
  console.log("Ex It")
  res.render('website/index', { 'data': data });
});

Answered By – Bobby Morelli

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published