使用 nodejs fs.rename 移动文件,导致输出文件为空

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

提问人:Eugene1111 提问时间:11/13/2023 更新时间:11/13/2023 访问量:10

问:

我正在制作一个 vscode 扩展,它应该将特定文件从一个项目的目录移动到另一个项目目录。当它这样做时,随机一个或多个文件可能会变成空白。为什么?如何解决?我想这可能与一些磁盘缓冲区有关。也许不是..甚至可能是Windows Defender?我想不是......如果是这样的话,也许有一种方法可以等待 idk 清空缓冲区......简而言之,第一部分甚至是为了了解导致错误的原因...... 即使代码没有经过 catch 语句,也会发生这种情况,因此在成功的 fs.rename 解析时也会发生这种情况

代码如下

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);
    });
node.js 文件 file-io vscode-extensions node.js-fs

评论


答: 暂无答案