重命名没有正确分配名称的文件

Posted

技术标签:

【中文标题】重命名没有正确分配名称的文件【英文标题】:Renaming file not having proper assigned name 【发布时间】:2022-01-24 01:25:24 【问题描述】:

我试图查看某个目录,当一个新文件添加到该目录时,我想重命名该文件,但它不起作用。问题是目录监视部分工作正常,但是当我重命名新添加的文件时,我给它的名称会被迭代并给它错误的名称。例如,如果我分配的新名称是thisIsName,当它被重命名时,它会变成thisIsNamethisIsNamethisIsNamethisIsName。我怎样才能使它重命名为指定的名称而无需任何迭代?任何帮助表示赞赏。提前致谢。

const fs = require("fs");
const chokidar = require('chokidar');

const watcher = chokidar.watch('filePath', 
  ignored: /(^|[\/\\])\../,
  persistent: true
);

function yyyymmdd() 
  var now = new moment();
  return now.format("YYYYMMDD");


function hhmmss() 
  var now = new moment();
  return now.format("HHmmss");


const log = console.log.bind(console);
//watching a certain directory for any update to it
watcher
  .on('add', path => 
    const newFileName = "filePath\\" + yyyymmdd() + hhmmss() + path
    //trying to rename the file, but its not working because newFileName is somehow getting looped and having multiple iterations of the DATE and TIME in the new name when getting renamed. Example of what the product looks like is included above in the question. 
    fs.renameSync(path, newFileName);
  )
  .on('change', path => 
    log(`File $path has been changed`)
  )
  .on('unlink', path => 
    log(`File $path has been removed`)
  )

【问题讨论】:

【参考方案1】:

我对您的代码做了一些小改动,它适用于任何文件格式(也适用于未格式化的文件)。无论如何,随心所欲地使用。您唯一错过的是“路径”的用法:

const moment = require('moment');
const fs = require('fs');
const chokidar = require('chokidar');
const path = require('path');
const log = console.log.bind(console);

function formattedDate() 
    return moment().format('YYYYMMDDHHmmss');


// here I've used some folder with name "folder" in the same directory as this file 
const filePath = path.join(__dirname, `./folder`);
const watcher = chokidar.watch(filePath, 
    ignored: /(^|[\/\\])\../,
    persistent: true
);

watcher
    .on('add', addedFilePath => 
        const fileExt = path.extname(addedFilePath);
        const newFilePath = path.join(__dirname, `./folder/$formattedDate()$fileExt`);
        fs.renameSync(addedFilePath, newFilePath);
    )
    .on('change', changedFilePath => 
        log(`File $changedFilePath has been changed`);
    )
    .on('unlink', removingFilePath => 
        log(`File $removingFilePath has been removed`);
    );

这里是东西:

【讨论】:

您确定名称迭代已停止,因为我复制了它,但得到的结果与以前相同 我附了个gif,有全过程 哦,迭代正在发生,因为我在newFilePath 字符串的末尾包含了addedFilePath。您对我如何做同样的事情有任何想法,但将addedFilePath 添加到newFilePath 的末尾。即YYYYMMDDHHmmss + addedFilePath 顺便说一句 addedFilePath 是一个路径,所以我将它切片以从路径中获取文件名,然后 YYYYMMDDHHmmss + the sliced file name 但它是迭代的 你使用类似 nodemon 的东西吗?

以上是关于重命名没有正确分配名称的文件的主要内容,如果未能解决你的问题,请参考以下文章

使用 dplyr 重命名未命名的变量

如何批量重命名文件夹下的Excel文件

用PHP重命名$ _FILES(文件)

如何重命名android包名称? [复制]

如何在 HIVE 的分区中重命名文件

使用元数据名称批量重命名文件