Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js 'fs' - More efficient way to create file + clear file

Tags:

node.js

fs

At the moment I am using fs.createWriteStream(filePath) to do two things:

  1. Create the file if it doesn't exist
  2. Clear/delete the contents of the file

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?

like image 495
Alexander Mills Avatar asked May 12 '16 03:05

Alexander Mills


2 Answers

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

like image 57
Atul Agrawal Avatar answered Sep 26 '22 00:09

Atul Agrawal


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.

like image 21
jfriend00 Avatar answered Sep 25 '22 00:09

jfriend00