Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between fs.writeFile and fs.writeStream

Tags:

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.

like image 654
Yijinsei Avatar asked Jan 07 '12 10:01

Yijinsei


People also ask

What is the difference between FS writeFile and FS writeFileSync?

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.

What is the use of writeFile 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.

Does FS writeFile overwrite?

fs. writeFileSync and fs. writeFile both overwrite the file by default. Therefore, we don't have to add any extra checks.

Does FS writeFile create a file?

The fs. writeFileSync() creates a new file if the specified file does not exist.


1 Answers

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.

like image 183
thejh Avatar answered Oct 07 '22 09:10

thejh