Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 815
javorosas Avatar asked Oct 20 '22 08:10

javorosas


1 Answers

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');
like image 165
Jack Avatar answered Nov 03 '22 01:11

Jack