且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ENOENT,没有这样的文件或目录,但文件存在

更新时间:2023-02-22 21:37:44

出现错误后,文件的名称是旧名称还是新名称? (我曾经遇到过两个线程被意外启动,而第二个发现文件已经消失的情况).目标目录是否存在?有错别字吗?

After the error, is the file there by the old name or the new name? (I've had cases where two threads were inadvertenly started, and the second found the file already gone). Does the target directory exist? Any typos?

这是Linux手册页关于重命名的内容:

Here's what the linux manpage says about rename:

ENOENT由oldpath命名的链接不存在;该链接不存在.或newpath中的目录组件 不存在;或者,oldpath或newpath是一个空字符串.

ENOENT The link named by oldpath does not exist; or, a directory component in newpath does not exist; or, oldpath or newpath is an empty string.

这是一个nodejs错误,它报告实际上是问题的目标目录时缺少源文件.要从命令行重现:

this is a nodejs bug, it reports that the source file is missing when it's actually the destination directory that's the problem. To reproduce from the command line:

% touch /tmp/file.txt
% node -p 'fs = require("fs"); fs.renameSync("/tmp/file.txt", "/nonesuch/file.txt");'

它打印:

Error: ENOENT, no such file or directory '/tmp/file.txt'
    at Object.fs.renameSync (fs.js:548:18)
    at [eval]:1:24
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:456:26)
    at evalScript (node.js:536:25)
    at startup (node.js:80:7)
    at node.js:906:3

这是包装renameSync()来解决此问题的一种可能方法(未经测试!)

here's a possible way to wrapper renameSync() to fix this (untested!)

var _origRename = fs.renameSync;
fs.renameSync = function(from, to) {
    try { _origRename(from, to) }
    catch (err) {
        if (err.stack.indexOf('ENOENT') < 0) throw err;
        try { fs.statSync(from) } catch (err2) { throw err }
        throw new Error("ENOENT, no such file or directory '" + to "'");
    }
}