I'm attempting to write to a .txt file using the FileSystem module NodeJS provides. However, this it is not running and it's not showing any errors. Upon further expection, I can also tell that read/writeFileSync's callback is not being ran.
utils.js
writeFile(path,encoding)
{
console.log('debug write')
fs.writeFileSync(path,encoding,(err)=>{
if(err) console.log(this.errorCodes.state.err004);
else console.log('success');
return;
});
return;
}
readFile(path,encoding)
{
console.log('debug read')
return fs.readFileSync(path,encoding,(err)=>
{
if(err) console.log(this.errorCodes.state.err004)
});
}
state.js
//returns data from state
async get(key)
{
//root not updating to interact with state
this.utils.readFile('./tempRoot.txt','utf8');
console.log(this.root)
const value = await this.trie.get(Buffer.from(key));
console.log(value.toString())
return
}
//sets data in state
async set(key,value)
{
await this.trie.put(Buffer.from(key),Buffer.from(value));
this.setRoot();
return;
}
//set root of state
setRoot()
{
const root = this.getRoot().toString('hex');
console.log(root)
this.utils.writeFile('./tempRoot.txt',root);
}
My guess is that the synchronous operation is being called in an async function but I don't understand why that would have an effect as it would just await then execute the file write/read functions?
Questions: What am I doing wrong? And if it's the async function, then how would that have an impact?
As I don't have enough reputation to comment, I'll link the answer: fs.writeFileSync doesn't take a callback
fs.writeFileSync function does not take an argument to pass a callback function, rather it throws an error to be caught; see the documentation: fs.writeFileSync
Callback functions run after another function has finished its execution. Such waiting is needed for asynchronous functions, that execute independently. Synchronous functions, on the other hand, block the control flow, eliminating the need for callback functions.