-2
function LoadMapFromText(route){

  var str = '';
  
  fs.readFile(route, (err, data) => {
    str = data.toString();
  });

  var pairs = str.split("-n");

  console.log(str);
}

ive been trying to fix this problem for god knows how long, and i just don't know how to do it. the string is not updating from inside the arrow function.

i already tried making the function async, and i already tried putting await before fs.readFile, but to no avail. i am at a loss of what to do.

Dexygen
  • 12,287
  • 13
  • 80
  • 147

2 Answers2

-1

The problem is that fs.readFile is an asynchronous function that implements a callback function. The callback function gets executed only after the file has been read. In your case, your "arrow function" is the callback function, which gets executed only after the file has been read. But by this time, the lines following the callback, including your console.log(str) statement, have already been executed.

Try using fs.readFileSync instead.

function LoadMapFromText(route){

  var str = fs.readFileSync(route, 'utf8');

  var pairs = str.split("-n");

  console.log(str);
}
nirinsanity
  • 141
  • 1
  • 5
-1

You should use the function fs.readFileSync() in the proposed case if it is a light file, otherwise you should use the callback of fs.readFile with a promise, so your string was not updated.

function LoadMapFromText(route){

  let str = '';
  
  str = String(fs.readFileSync(route))

  var pairs = str.split("-n");

  console.log(str, pairs);
}