简体   繁体   中英

What happens when you delete a file which is open as writeStream by fs module in nodejs?

I was downloading some files and writing it to a file which is opened as writeStream but when I tried to delete it, it got deleted but fs was still doing its job but writing nowhere... Where that buffer is going?? as I deleted that file in which it was writing

If you are on a UN*Xy OS, a deleted file continues to exist until all file descriptors open to it are closed. It exists, but it has no name.

" What happens to an open file handle on Linux if the pointed file gets moved or deleted " gives details on Linux.

I think the general answer is JS just keeps the writing data chunks in the heap and release them at the proper moment under its garbage collection mechanism.

The writing data chunk could be one of types <string> | <Buffer> | <Uint8Array>...<string> | <Buffer> | <Uint8Array>... <string> | <Buffer> | <Uint8Array>... , maybe you want to have a look on API Buffer.allocUnsafeSlow(size) , it mentions:

When using Buffer.allocUnsafe() to allocate new Buffer instances, allocations under 4KB are sliced from a single pre-allocated Buffer. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffer instances.

According to this paragraph, you can infer allocating memory for Buffer (Which is one of types I mentioned above) by another method Buffer.alloc() is under the garbage collection of Node engine.

The memory handling of JS Object is in the heap. The createStream must open and load the data of the dest file to the heap/memory first, even method like writeStream.write() , it doesn't mean it's directly doing I/O to the file/disk, it must handle the data chunk by chunk in the memory first, then use the least number of times to write it into the disk, so when the dest file is gone, probably the practice of this method just keeps these data chunks in the heap then see when is the good time to release them.

Compare to the situation the dest file still exists, I think there is no big difference, it would end up cleaning the memory for those data.

If you want to know more about garbage collection in Node engine: a-tour-of-v8-garbage-collection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM