Windows 10 ENOENT 4058 上的节点 fs.rename

Node on Windows 10 ENOENT 4058 with fs.rename

所以,我正在尝试编写一个小脚本来重命名目录中的文件。系统为 Windows 10,节点为 12.13.1 重命名过程应检查文件扩展名,然后增加文件的前缀。我有大部分逻辑,如果不雅地拼凑在一起,但我正在努力解决这个错误:

[Error: ENOENT: no such file or directory, rename 'C:\Projects\rename_apptest.txt' -> 'C:\Projects\rename_apptest.txt'] {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'rename',
  path: 'C:\Projects\rename_app\2test.txt',
  dest: 'C:\Projects\rename_app\1test.txt'
}

无论提供给重命名函数的参数的顺序如何,或者命令是否 运行 具有提升的权限,都会发生此错误。

这是删除了我的 console.logs 的代码的清理版本:

const path = require('path');
const fs = require('fs');
const directoryPath = path.join(__dirname, 'Documents');
fs.readdir(directoryPath, function (err, files) {
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    } 
    files.forEach(function (file) {
        suffix = file.substring(file.length -3);
        if(suffix === "txt"){
            prefix = file.charAt(0);
            if(!isNaN(prefix)){
                newPre = prefix++;
                newFile = file.replace(newPre, prefix);
                file1 = path.join(__dirname, file);
                newFile1 = path.join(__dirname, newFile);
                fs.rename(file1, newFile1, function(err){
                    if(err) throw err;
                    console.log('it worked?');
                })

            }

        } 
    });
});

四处寻找,我还没有想出解决办法,我试过使用renameSync,以及复制而不是重命名文件。有什么想法吗?

您正在 fs.readdir() 这条道路上:

const directoryPath = path.join(__dirname, 'Documents');

但是,当您将路径放回 fs.readdir() 的结果时,您只使用了 __dirname。您丢失了路径的 Documents 部分,因此您没有正确的路径。

我建议您更改:

            file1 = path.join(__dirname, file);
            newFile1 = path.join(__dirname, newFile);

对此:

            file1 = path.join(directoryPath, file);
            newFile1 = path.join(directoryPath, newFile);