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

Time:08-25

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"?

CodePudding user response:

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 });
});
  • Related