0

In the code below, content1 becomes undefined. I want it to equal 11111

const fs = require('fs');
fs.writeFile('./1.txt','11111',function(err,data{
  var content1 = fs.readFile('./1.txt',function(err,data){
    console.log(content1);
  });
});

2 Answers 2

2

readFile do not have a return value.

The contents of the read file will be in the parameter data of the callback function. You should also include the encoding in the options param so you can write/print the contents as text.

const fs = require('fs');
fs.writeFile('./1.txt','11111','utf8',function(err,data){
  fs.readFile('./1.txt','uft8',function(err, content1){
    console.log(content1);
  });
});
Sign up to request clarification or add additional context in comments.

Comments

0

Two things are actually missing in your code:

1- writeFile and readFile functions are both asynchronous the result is only accessible by a callback function or a promise if it is handled, so in the code below we are accessing the result using callback function.

2- Consider using 2 different names for the callback result from writeFile and readFile as you are using data in both of them.

try this:

const fs = require('fs');

fs.writeFile('./1.txt', '11111', function(err, writeData) {
    fs.readFile('./1.txt',  "utf8", function(err, readData) {
        console.log(readData);
    });
});

2 Comments

Answers with no explanation at all are never as good as answers that include some text explaining what was wrong with the original code.
you are right edited with my understanding to the issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.