windowsnode.jsunlink

Deleting file in Node.js


I am using node in a Windows environment. When I use fs.unlinkSync(fileName), it seems to work. After the unlinkSync statement is executed, if I do a fs.existsSync(filename) it returns false indicating the file does not exists, but when I go to the physical drive I can still see the file.

At this point in time if I try and delete the file manually, it throws Access denied. However, the file is automatically removed from the file system only when I stop the executing node script file.

Is this the expected behavior?


Solution

  • If the file has been opened and not closed within your NodeJS code, you'll encounter the behavior you're experiencing. It's behaving as expected, on Windows.

    Take this code for example:

    var fs = require('fs');
    
    var filename = "D:\\temp\\temp.zip";
    var tempFile = fs.openSync(filename, 'r');
    // try commenting out the following line to see the different behavior
    fs.closeSync(tempFile);
    
    fs.unlinkSync(filename);
    

    If the code uses openSync and then closeSync on the file, the file is immediately deleted when unlinkSync is called. If however, you were to remove the closeSync call, you'll find that the file is deleted only when the NodeJS process cleanly exits. This is just one example of a way to cause this problem to occur.

    If you're using a third party library that is processing files, etc., it's possible the code is not properly closing the file handles/descriptors and you would also encounter this issue (for the same reason).

    FYI: The file will appear to be deleted immediately if you test this code on a Linux based operating system. It's a difference in behavior between the operating systems and the way files are deleted.

    Details

    When NodeJS on Windows deletes a file, it's actually not calling an API to directly delete a file. Instead, it's using a low level function called ZwSetInformation (reference). With that function, it's setting a field called DeleteFile to TRUE for the specified file (handle). That's used so that when all file handles are closed for that file, it will be automatically deleted. Files in NodeJS are opened with the access mode of FILE_SHARE_DELETE so that they can be deleted properly by use of the other function.