Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Js: Test to see if a file is locked for editing by another process

I am writing some code in NodeJs, and want to check to see if the file is in use by another process, if it is then do nothing, if it isn't in use do something.

fs.stats is kind of a, at this instant what is the file size. And doesn't tell me me if its currently in use from another process.

Not sure what else to try.

What is the best way to tell if a file is currently locked for editing by another process, before trying to access the file using nodejs?

like image 501
shaun Avatar asked Dec 15 '22 05:12

shaun


1 Answers

Code I ended up using after some instruction from the comments left.

var delInterval = setInterval(del(), 1000);

function del(){
    fs.open(filePath, 'r+', function(err, fd){
        if (err && err.code === 'EBUSY'){
            //do nothing till next loop
        } else if (err && err.code === 'ENOENT'){
            console.log(filePath, 'deleted');
            clearInterval(delInterval);
        } else {
            fs.close(fd, function(){
                fs.unlink(filePath, function(err){
                    if(err){
                    } else {
                    console.log(filePath, 'deleted');
                    clearInterval(delInterval);
                    }
                });
            });
        }
    });
}
like image 134
shaun Avatar answered Dec 31 '22 02:12

shaun