Yijinsei
Yijinsei

Reputation: 788

Difference between fs.writeFile and fs.writeStream

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.

Upvotes: 23

Views: 13090

Answers (1)

thejh
thejh

Reputation: 45578

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.

Upvotes: 34

Related Questions