In Node.js, you can use the built-in fs
(file system) module to write to a file. Here's an example code snippet that demonstrates how to write to a file synchronously:
index.tsx189 chars11 lines
In the above code, we first require the fs
module. Then we define the data we want to write to the file. We use the fs.writeFileSync
method to write the data to the file synchronously. If an error occurs, we catch it and log it. If the write is successful, we log a success message.
Note that fs.writeFileSync
will replace the contents of the file if it already exists, otherwise it will create a new file. If you want to append data to an existing file, you can use the fs.appendFileSync
method instead.
Here's an example code snippet that demonstrates how to write to a file asynchronously:
index.tsx205 chars12 lines
In the above code, we use the fs.writeFile
method to write the data to the file asynchronously. If an error occurs, we log it. If the write is successful, we log a success message.
gistlibby LogSnag