3

I cannot find any solution for this problem. Using Node fs I create a file with createWriteStream, write data to it and then try to delete it but it cannot be deleted while node is open.

The following is the code I am using for this process:

var file = fs.createWriteStream("test.txt", {flags: "a"); file.write(new Buffer(1048576)); 

The file is created with success and the 1MB of empty data is written to it correctly. The problem is when I try to fs.unlink the file or delete it manually (Windows - Delete file), it disappears from the folder but once I refresh the folder the file is still there, it is always there until Node is closed. I think it gets marked for deletion once it is no longer in use by Node.

I've tried closing the file after the process with file.close(), file.end(), file.emit("close"), file.emit("end") and a few others but still could not delete the file.

How can I "finish" the file so that it can be deleted when I need to? I thought it closed itself after being written to.

2 Answers 2

2

Alas after experimenting different code combinations I managed to find a way to properly close the file if it is not being closed by itself as it does when you pipe stream data into the file from HTTP(s) get requests.

The correct way to close the file is with the following

fs.close(fd); 

The fd is the file descriptor and took me a while to understand where it was located. I tried using the file from my code example but it returned the error

fd must be a file descriptor

Eventually I stumbled into the file's file descriptor, it is just a number. You can find it in the file reference you have. In my case all I had to do was

fs.close(file.fd); 

And done, now the file can be deleted.

A callback can be used for the second argument if anyone wants: https://nodejs.org/api/fs.html#fs_fs_close_fd_callback

Sign up to request clarification or add additional context in comments.

Comments

1

To know when the underlying file descriptor has been closed, you need to listen for the close event after .end() has been called. For example:

var file = fs.createWriteStream("test.txt", {flags: "a"); file.on('close', function() { console.log('fd closed'); }); file.end(new Buffer(1048576)); 

1 Comment

Already tried that, it did not work. Fortunately I was able to find the solution for my problem and posted the answer already. Thanks for the help nonetheless.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.