5

I'm working on a node-webkit app that performs filesystem operations. I need to be able to check if the file is being used by another process before deleting (unlinking).

If I only use the fs.unlink method, the system will wait until the file stops being used before removing it completely. What I want is that if the file is being used, don't wait until it's released, but cancel the whole operation and don't delete it.

Thanks.

javorosas
  • 759
  • 1
  • 12
  • 22
  • 1
    What happen if you delete the file with a synchronous operation. Do you get an error or it blocks your script? – Krasimir May 23 '14 at 04:11
  • I am stuck in a similar situation therefore, I can say that the file won't get deleted unless it is released. Releasing here also means stopping the server which is not something ideal to do. – Neeraj Sewani Oct 27 '21 at 08:15

1 Answers1

3

Assuming you're on a *nix system something like this should work. Obviously this is overly simplified as far as error and path checking. There may very well be a better way to do this but I might as well start the discussion with this:

var fs = require('fs'),
    exec = require('child_process').exec;

function unlinkIfUnused(path) {
    exec('lsof ' + path, function(err, stdout, stderr) {
        if (stdout.length === 0) {
            console.log(path, " not in use. unlinking...");
            // fs.unlink...
        } else {
            console.log(path, "IN USE. Ignoring...");
        }
    });
}

unlinkIfUnused('/home/jack/testlock.txt');
Jack
  • 20,735
  • 11
  • 48
  • 48