【问题标题】:Fs.renameSync throws Error: ENOENT while renaming, but the file existsFs.renameSync 抛出错误:重命名时 ENOENT,但文件存在
【发布时间】:2020-12-04 19:59:27
【问题描述】:

为什么 fs.Renamesync 会在这里抛出错误:

this.parentDirectory = path.join(__dirname, '..', '..', 'Logs', serverType + '-logs');
this.logFilePath = path.resolve(this.parentDirectory, 'latest.log');
if (fs.existsSync(this.logFilePath)){
  var newName = await firstLine(this.logFilePath);
  newName += '.log';
  fs.renameSync(this.logFilePath, path.join(this.parentDirectory, newName));
}

它是这样说的:

(node:648) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, rename 'D:\Unity\Projects\FlipSide\Logs\room-logs\latest.log' -> 'D:\Unity\Projects\FlipSide\Logs\room-logs\Log-room-2020-08-14T22:58:20Z.log'

(不,这不是unity脚本,它是一个独立的节点服务器。)

文件存在,但不会重命名。

【问题讨论】:

  • target路径下的所有目录都存在吗? ENOENT 可能是关于它们的,而不是源文件。
  • @9000 是的,它只在文件存在时重命名,如果所有目录都不存在,它会在 existsSync 处抛出错误......对吧......?

标签: node.js fs


【解决方案1】:

一个正确的答案,因为示例不适合 cmets。

我怀疑 destination 目录不存在,也可能比它高几级。

cd /tmp
mkdir -p a/b/c   # A few levels exist.
touch a/foo.bar  # Our source file definitely exists. 
node
# Welcome to Node.js v13.2.0.

现在在 Node REPL 中:

const fs = require('fs')
// The destination directory does not exist, many levels of it.
fs.renameSync('a/foo.bar', 'a/b/c/d/e/f/g/foo.bar')
Thrown:
Error: ENOENT: no such file or directory, rename 'a/foo.bar' -> 'a/b/c/d/e/f/g/foo.bar'
    at Object.renameSync (fs.js:659:3) {
  errno: -2,
  syscall: 'rename',
  code: 'ENOENT',
  path: 'a/foo.bar',
  dest: 'a/b/c/d/e/f/g/foo.bar'
}

不,异常消息从不指定它是源还是目标。

【讨论】:

  • 嗯,它在同一个目录中移动。而且既然文件存在,那么目录显然也存在。
猜你喜欢
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
相关资源
最近更新 更多