0

i dont know how i can pass some information into a GET in node. I have a .txt file and sometimes have a change in this file, so, i want to show this change when i enter in my webpage, but the change only occurs when the server refresh.

var itens = func.readfile();

app.get("/inventario", function(req, res){
  res.format({
    html: function(){
      res.render('inventario', {itenss: func.readfile()});
    }
  });

i have a variable that receive a data from a function in other file.

exports.readfile = function() {
  var texto = [];
  fs.readFile('./static/itens.txt', function(err, data) {
    if (err) {
      return console.error(err);
    }

    var palavra = '';
    var linha = [];

    for (var i = 0; i < data.length; i++) {
      if (data[i] != 10) {
        palavra = palavra + (String.fromCharCode(data[i]));
      } else if (data[i] == 10) {
        texto.push(palavra);
        palavra = [];
      }
    }
    console.log(texto);
  });
  return texto;
}

so if the variable is out of scope, the page can receive the data and show in html file, but, i want to refresh the data in array case i refresh the page and the new information in .txt file is shown too

Barmar
  • 741,623
  • 53
  • 500
  • 612
Lukas Kun
  • 3
  • 1

1 Answers1

0

fs.readFile() is asynchronous. That means that when you call the function, it starts the operation and then immediately returns control back to the function and Javascript busily executes more Javascript in your function. In fact, your readFile() function will return BEFORE fs.readFile() has called its callback. So, you cannot return the data directly from that function. Instead, you will need to either return a promise (that resolves when the data is eventually available) or you will need to communicate the result back to the caller using a callback function.

See this answer: How do I return the response from an asynchronous call? for a lot more info on the topic.

You can modify your readFile() function to return a promise (all async functions return a promise) like this:

const fsp = require('fs').promises;

exports.readfile = async function() {
  let texto = [];
  let data = await fsp.readFile('./static/itens.txt');

  let palavra = '';
  let linha = [];

  for (var i = 0; i < data.length; i++) {
    if (data[i] != 10) {
      palavra = palavra + (String.fromCharCode(data[i]));
    } else if (data[i] == 10) {
      texto.push(palavra);
      palavra = [];
    }
  }
  console.log(texto);
  return texto;
}

And, then you can use that function like this:

app.get("/inventario", function(req, res){
  res.format({
    html: function(){
      func.readFile().then(data => {
          res.render('inventario', {itenss: data});
      }).catch(err => {
          console.log(err);
          res.sendStatus(500);
      });
    }
});

For performance reasons, you could also cache this result and cache the time stamp of the itens.txt file and only reread and reprocess the file when it has a newer timestamp. I'll leave that as an exercise for you to implement if it is necessary (may not be needed).

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • ok, this fix my problem, i will read more about async/await and understand this and try cache the result for training. Tanks so much. – Lukas Kun Jan 04 '20 at 01:54