moving files with nodejs fs.rename resulting in empty output files

25 Views Asked by At

I'm making a vscode extension, and it should move particular files from one project's directory into another. And when it does it, randomly one or several files might become blank.... Why? How to fix it? I guess it's related to some disk buffers maybe.. maybe not.. maybe even to windows defender? I guess not... Maybe there is a way to wait for idk for buffer to be emptied if it's even the case... In short the first part is even to get what causes the bug... it happens even when the code is not going through the catch statements, so it happens on successful fs.rename resolving

here's the code

const scopeFileContent = await readFile(scopeFiles[0].fsPath, 'utf8');
const lines = scopeFileContent.split('\n');

for await (let line of lines) {
    if (line.replace('\r', '').length === 0) {
        continue;
    }
    const scopeFileName = path.basename(line.replace('\r', ''));

    let oldPath = line.toString()[0] === '/' ? thePath + line.replace('\r', '') : thePath + '/' + line.replace('\r', '');
    const newPath = thePath + '/src/scope/' + scopeFileName;

    await new Promise(async (resolve, reject) => {
        let success = false;
        while (!success) {
            try {
                // console.log('CURRENT FILE', path.basename(line));
                await rename(oldPath, newPath);
                success = true;
            } catch (error: any) {
                if (error.message.includes('ENOENT')) {
                    console.log('Wrong path, searching for the file');
                    const scopeFiles = await workspace.findFiles(`**/${scopeFileName}`, `{${excludePattern.join(',')}}`);
                    if (scopeFiles.length === 0) {
                        throw Error('File from the scope not found, aborting...');
                    } else if (scopeFiles.length > 1) {
                        throw Error('Duplicate from the scope found. Aborting');
                    }
                    oldPath = scopeFiles[0].fsPath;
                } else {
                    // if error is about file busy or sth
                    console.log(error);
                    await new Promise((r) => setTimeout(r, 1000));
                }
            }
        }
        resolve(true);
    });
0

There are 0 best solutions below