Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  182] [ 6]  / answers: 1 / hits: 23635  / 10 Years ago, sat, june 28, 2014, 12:00:00

I'm writing a purely synchronous, single threaded command line program in node.js, which needs to write a single binary file, for which I'm using WriteStream. My usage pattern is along the lines of:



var stream = fs.createWriteStream(file)
stream.write(buf1)
stream.write(buf2)


This seems to work, but the documentation says it's asynchronous and I want to make sure I'm not writing code that works 99% of the time. I don't care exactly when the data gets written as long as it's written in the specified order and no later than when the program exits, and the quantity of data is small so speed and memory consumption are not issues.



I've seen mention of stream.end() but it seems to work without it and I've also seen suggestions that calling it may actually be a bad idea if you're not using callbacks because it might end up getting called before all the data is written.



Is my approach correct (given that I want purely synchronous) or is there anything I need to watch out for?


More From » node.js

 Answers
11

You can do this, the only problem can be if you create two or more concurrent streams for the same path: the order of writes from different streams will be undefined. By the way, there is a synchronous fs write stream implementation in node: fs.SyncWriteStream. It's kind of private and requires fd as an argument, but if you really want it...


[#70390] Thursday, June 26, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
quinlanhenryf

Total Points: 743
Total Questions: 93
Total Answers: 118

Location: Australia
Member since Sat, May 27, 2023
1 Year ago
;