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.
import {fs} from "fs" function App() { async function syncItems(){ console.log("Sync start test") // This line prints fs.writeFile("/tmp/test", "Hey there!", function(err) { if(err) { return console.log(err); } console.log("The file was saved!"); }); console.log("Sync end test") / This line doesn’t print } return ( <Button color="success" onClick={() => { syncItems(); }}> Sync </Button> ); }
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.
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'writeFile') at syncItems (App.js:54:1) at Object.onClick (App.js:189:1) at Button.onClick (Button.js:42:1) at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1) at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1) at invokeGuardedCallback (react-dom.development.js:4056:1) at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4070:1) at executeDispatch (react-dom.development.js:8243:1) at processDispatchQueueItemsInOrder (react-dom.development.js:8275:1) at processDispatchQueue (react-dom.development.js:8288:1) at dispatchEventsForPlugins (react-dom.development.js:8299:1) at react-dom.development.js:8508:1 at batchedEventUpdates$1 (react-dom.development.js:22396:1) at batchedEventUpdates (react-dom.development.js:3745:1) at dispatchEventForPluginEventSystem (react-dom.development.js:8507:1) at attemptToDispatchEvent (react-dom.development.js:6005:1) at dispatchEvent (react-dom.development.js:5924:1) at unstable_runWithPriority (scheduler.development.js:468:1) at runWithPriority$1 (react-dom.development.js:11276:1) at discreteUpdates$1 (react-dom.development.js:22413:1) at discreteUpdates (react-dom.development.js:3756:1) at dispatchDiscreteEvent (react-dom.development.js:5889:1)
Advertisement
Answer
Your import statement is incorrect.
You can either import fs
entire module:
import fs from 'fs'; fs.writeFile(/*...*/);
Or import a function from the module:
import { writeFile } from 'fs'; writeFile(/*...*/)
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
:
async function syncItems(){ console.log("Sync start test"); await fs.promises.writeFile("/tmp/test", "Hey there!") .catch((err) => { console.log(err) }); console.log("The file was saved!"); console.log("Sync end test") return ( <Button color="success" onClick={() => { syncItems(); }}> Sync </Button> ); }