Reputation: 2719
I have fs.writeFileSync and fs.readFile operation for my app to work. I have put both these operations under promise. I process other statements only after these promises are resolved. What I have observed is read is happening before write has completed
Here is my code snippet
To illustrate the above problem I have created a code snippet that writes random number to a file and later it will read file. If the file content is same as latest generated random number. Then read and write is synchronized.
file.js
let fs = require('fs');
let fileContent;
let randomNumbers = Math.ceil(Math.random() * 10);
function test (filepath) {
(async () => {
await writefile(filepath);
param = await readfile(filepath);
console.log(param);
}) ();
}
function writefile(filepath) {
let promise;
promise = new Promise((resolve,reject) => {
fs.appendFileSync(randomNumbers,filepath);
})
return promise;
}
function readfile(filepath) {
let promise;
promise = new Promise((resolve,reject) => {
fileContent = fs.readFileSync(filepath);
if( fileContent == randomNumbers ) {
console.log("file read and write is synchronized");
} else {
console.log("file read and write is not synchronized");
}
})
return promise;
}
Upvotes: 0
Views: 615
Reputation: 108641
I believe you're misusing your Promise objects.
await writeFile(path)
won't complete until you call the resolve()
method in your Promise function.
Maybe you should change writeFile()
function to look like this, and make a similar change to readFile()
.
function writefile(filepath) {
return new Promise((resolve,reject) => {
fs.appendFileSync(randomNumbers,filepath);
resolve()
})
}
But, it has to be said, the sync functions in fs
get rid of the need for promises. So you could do this just as easily.
function test (filepath) {
fs.appendFileSync(randomNumbers,filepath);
fileContent = fs.readFileSync(filepath);
console.log(fileContent);
}
Or you could wrap the async functions in promises, like this:
function writefile(filepath) {
return new Promise((resolve,reject) => {
fs.appendFile(randomNumbers,filepath, (err, result) => {
if (err) reject(err);
else resolve(result);
});
})
}
That's called promisifying the function.
Upvotes: 1