Reputation: 986
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 :
Upvotes: 0
Views: 1164
Reputation: 3998
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.
Upvotes: 2
Reputation: 1977
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.
Upvotes: 2
Reputation: 6546
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.
Upvotes: 2