quino0627
quino0627

Reputation: 145

How to use writeFile and readFile together in node js

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

Upvotes: 0

Views: 1283

Answers (2)

rckrd
rckrd

Reputation: 3364

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

Upvotes: 2

Amr Labib
Amr Labib

Reputation: 4083

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

Upvotes: 0

Related Questions