I'm a little confused between the 2 methods, hope somebody could enlighten
me on the difference between fs.open->fs.write
, fs.writeFile
, fs.writeStream
.
The fs. writeFileSync() is a synchronous method & creates a new file if the specified file does not exist while fs. writeFile() is an asynchronous method.
writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The 'options' parameter can be used to modify the functionality of the method.
fs. writeFileSync and fs. writeFile both overwrite the file by default. Therefore, we don't have to add any extra checks.
The fs. writeFileSync() creates a new file if the specified file does not exist.
fs.open
and fs.write
are for low-level access, similar to what you get when you code in C. fs.open
opens a file and fs.write
writes to it.
A fs.WriteStream
is a stream that opens the file in the background and queues writes until the file is ready. Also, as it implements the stream API, you can use it in a more generic way, just like a network stream or so. You'll e.g. want this when a user uploads a file to your server - take the incoming HTTP POST stream, pipe()
it to the WriteStream
. Very easy.
fs.writeFile
is a high-level method for writing a bunch of data you have in RAM to a file. It doesn't support streaming or so, so it's a bad idea for large files or performance-critical stuff. You'll want this if you write out small JSON files or so in your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With