javorosas
javorosas

Reputation: 769

Node js check if file is being used by another process

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.

Upvotes: 5

Views: 2778

Answers (1)

Jack
Jack

Reputation: 21163

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');

Upvotes: 3

Related Questions