0

I am writing a node js program to read content from a file , I am executing this program multiple times in a short time. Sometimes I can see file content and sometimes I do not (PFA screenshot) , can anyone please explain why this is happening ? Is this because I am not using promises ?

var fs= require('fs');
fs.readFile('myData.json', (err, data) => {
  if(err)
    console.log('Error Found',err.code);
  else {
    console.log('inside else');
    fs.open('myData.json', 'wx', (err, fd) => {
      console.log('inside open file');
      fs.writeFile('myData.json','test data',(err)=>{
        if(err) console.log('error writing data');
      });
      fs.readFile('myData.json','utf8',(err, data) => {
        console.log('read file'+data);
      });
    });
  }
});

Screen Shot :

enter image description here

2
  • I don't see that you're closing the file after reading/writing. I believe it's good practice to make sure the file is closed before moving on and maybe that's why it fails inconsistently. Commented Dec 5, 2017 at 14:24
  • You start to read, wait for that, start to open, wait for that, then write and read at the same time. Maybe some cleaner indentation would help. Commented Dec 5, 2017 at 14:28

3 Answers 3

2

Can you try after fixing following code

fs.writeFile('myData.json','test data',(err)=>{
  if(err) console.log('error writing data');
  fs.readFile('myData.json','utf8',(err, data) => {
    console.log('read file'+data);
  });
});

You have placed read file in async with write file. You need to read file after writing it.

Sign up to request clarification or add additional context in comments.

Comments

2

fs.readFile and fs.writeFile are asynchronous. You start the readFile immediately after calling writeFile. This means writeFile may or may not (probably not) have time to finish before readFile executes.

Try putting the readFile within the writeFile callback. The callback is called after the asynchronous function completes, so it allows you to handle code in a synchronous manner.

I'm not sure the readFile -> open -> writeFile -> readFile logic makes a lot of sense, though.

1 Comment

You are right , readFile -> open -> writeFile -> readFile makes no sense . I am new to Async programming and Node JS was trying something very random , thanks for your comment
2

Using latest Node.js v9.2.0 Documentation

fs.writeFile(file, data[, options], callback)

...

Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.

Since you wanna writeFile synchronous you should use

fs.writeFileSync(file, data[, options])

...

The synchronous version of fs.writeFile(). Returns undefined.

Comments

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.