Skip to content
Advertisement

‘Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘writeFile’)’ error while trying to write to a file with REACT

I am trying to write to a file with a button click inside my React application and it gives an error.

My current code looks like this.

JavaScript

Once I click the SYNC button it gives this error. This might be a noob mistake since I am new to this. I’d really appreciate if someone could help.

JavaScript

Advertisement

Answer

Your import statement is incorrect.

You can either import fs entire module:

JavaScript

Or import a function from the module:

JavaScript

Note that your code will not produce the desired output because fs.writeFile is an asynchronous function, which callback only gets executed once the operation completed. So this is what is going to be printed:

Sync start test
Sync end test
The file was saved!

Since you are in an async function, I would recommend using fs.promises.writeFile:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement