At the moment I am using fs.createWriteStream(filePath)
to do two things:
However, I never actually write to the stream, so I am not really using it. I am wondering how kosher this is, and if I should use a more efficient or more explicit method of creating the file if it doesn't exist and clearing the file out. Any ideas?
You can directly use
fs.writeFile('file path',<data to write>,'encoding',callback) //in your case data is empty
It will create the file if it does not exists and if exists then fist clear the contents and the add new contents to it
Per your request, posting my comment as an answer...
fs.open(filePath, 'w+')
using either the 'w'
or 'w+'
flags will also create/truncate the file.
I don't think it will actually give you a different result than your fs.createWriteStream(filePath)
and the code execution difference is probably insignificant, especially given that there's disk I/O involved. But, it might feel a little bit cleaner since it isn't setting up a stream that you aren't going to use.
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