0

I'm trying to make a function that checks if file is opened or in use by another app or process using fs

and here is my attempt to do this

function isFileInUse() {
    try {
        const file = path.join(__dirname, '20200201072955946-2.jpg');
        //try to open file for checking if it is in use
        fs.access(file, fs.constants.W_OK, (err) => {
            if (err) {
                console.log('File is in use');
            } else {
                console.log('File is not in use');
            }
        });
        return false;
    }
    catch(error) {
        console.log(error);
        return true;
    }
}
isFileInUse()

this code somehow move the the image with no error even if it's run by another app like notepad++ or by image viewer

if someone can tell me what i'm doing wrong on this matter or help with this . that be great

thanks in advance

KingDark
  • 27
  • 1
  • 6
  • Is this question about how to move a file or to check if the file is somwhere opend? And: Has this to be cross platform compatible? If no, what platform/OS are you using? Perhaps this is usefull: https://stackoverflow.com/a/28588960/5781499 – Marc Jan 02 '22 at 19:08
  • @Marc i'm trying to check if it's been used by another app and since a file can't be moved while in used that's why i went for moving approche . about crossplatform it should work for both linux and windows only pathes should look a bit difrrant but other than that that's the only os i run on and currently testing on windows if that's what u want to ask about – KingDark Jan 02 '22 at 19:37
  • Did you see my link? Thats exactly what is done there, use the `fs.open` method with "r+" mode. – Marc Jan 02 '22 at 20:21
  • This is the wrong approach. You can't properly pre-flight things involving another process because that just creates a race condition where the file becomes busy between the time you pre-flighted it and the time you try to use it. Instead, you need to attempt the operation you want to do and handle errors properly if there is file contention. In other words, in a multi-process situation, you can't pre-flight stuff that involves any other process. – jfriend00 Jan 02 '22 at 21:51
  • @Marc I have tried all the approaches in that link already and it's always the same the image is opened but still, i can move it or access it with no error – KingDark Jan 03 '22 at 09:20

0 Answers0