FS rename file - Error: ENOENT: no such file or directory, rename '24.png' -> '1.png'

FS rename file - Error: ENOENT: no such file or directory, rename '24.png' -> '1.png'

我正在尝试编写一个小脚本来重写我文件夹中图像的文件名。

我哪里错了?

我收到此错误: FS 重命名文件 - 错误:ENOENT:没有这样的文件或目录,重命名 '24.png' -> '1.png'

const fs = require('fs');

const fileNames = fs.readdirSync('./images')

for(const fileName of fileNames) {
    const ext = '.png'
    let incNumber = 1;
    let newName = String(incNumber + ext);
    fs.renameSync(fileName, newName);
    incNumber++
}

在将字符串添加到数字中时,无需将数字更改为字符串。如果您想确定可以致电 incNumber.toString() + ext

const fs = require('fs');
const path = require("path");
const fileNames = fs.readdirSync('./images')
const ext = '.png'
let incNumber = 1;
for(const fileName of fileNames) {
    let newName = path.join('./images', incNumber + ext);
    fs.renameSync(path.join('./images',fileName), newName);
    incNumber++
}

如果还需要按创建日期排序:

const fs = require('fs');
const path = require("path");
const dir = './allHorses';

console.log(dir);

const ext = '.png'
let incNumber = 1;

fs.readdir(dir, function(err, files){
    
    files = files.map(function (fileName) {
      return {
        name: fileName,
        time: fs.statSync(dir + '/' + fileName).mtime.getTime()
      };
    })
    .sort(function (a, b) {
      return a.time - b.time; })
    .map(function (v) {
      return v.name; });

      let files2 = files;

    for(const fileName of files2) {
        let newName = path.join('dir', incNumber + ext);
        fs.renameSync(path.join('dir',fileName), newName);
        incNumber++
    }
});