Reputation: 100506
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?
Upvotes: 6
Views: 10392
Reputation: 1520
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
Upvotes: 6
Reputation: 924
It's best to not open a file unless you're actually going to write to it. You could write some wrapper functions for open and write to delay opening the file until a write is needed.
var fd;
function open() {
if (fd) {
return;
}
fd = fs.open(filePath, 'w');
}
function write(buffer) {
if (!fd) {
open();
fs.writeFile(fd, buffer);
} else {
fs.write(fd, buffer);
}
}
write('open file and write');
write('write to already opened file');
When opening, use fs.open with the 'w' flag which means the file is created (if it does not exist) or truncated (if it exists).
Another way is for the write() function to call fs.writeFile when writing to the file for the first time, this will overwrite the existing contents of the file, and call the fs.write on subsequent writes to append.
In real terms there should be little performance difference between using writeFile() and write(), but it lets you avoid checking if the file exists, deleting it if it does, and creating a new file.
I'm assuming that you only have one process accessing this file at a time.
Upvotes: 2
Reputation: 708206
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.
Upvotes: 5