0

I am using fs mudule to read .txt file content , but the result always empty . My .txt file do has content in it could any one give me a hand pls ? This is my test code :

var fs = require("fs");

var content = "";
fs.readFile("2.txt", "utf8", function(err, data){
  if(err) {
    return console.log("fail", err);
  }
  content = data;
});

console.log(content);

The content is empty in console .

Jorge Wiston
  • 85
  • 1
  • 5
  • 2
    Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Klaycon Dec 13 '19 at 15:21
  • You can use [`fs.readFileSync`](https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options) if you want the synchronous version of `fs.readFile`. – TGrif Dec 13 '19 at 16:05

1 Answers1

1

You are writing the result too early. You should log the result in the readFile callback.

var fs = require("fs");

var content = "";
fs.readFile("2.txt", "utf8", function(err, data){
  if(err) {
    return console.log("fail", err);
  }
  content = data;
  console.log(content);
});
// The console log below will be executed right after the readFile call. 
// It won't wait the file to be actually read.
// console.log(content);

Or you can write the same logic like this:

const fs = require('fs');

async function main() {
  try {
    const content = await fs.promises.readFile('2.txt', 'utf8');
    console.log(content);
  } catch (ex) {
    console.trace(ex);
  }
}

main();
Mehmet Baker
  • 1,055
  • 9
  • 23