NodeJS-递归复制并重命名现有目录中的所有内容 [英] NodeJS - Copy and Rename all contents in existing directory recursively

查看:350
本文介绍了NodeJS-递归复制并重命名现有目录中的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个目录,其中包含文件夹和文件.我想将整个目录及其所有内容复制到其他位置,同时将所有文件重命名为更有意义的名称.我想使用nodejs完成这一系列操作.除了逐个移动并逐个重命名之外,还有什么简单的方法呢?

I have a directory with folders and files within. I want to copy the entire directory with all its contents to a different location while renaming all the files to something more meaningful. I want to use nodejs to complete this series of operations. What is an easy way to do it, other than moving it one by one and renaming it one by one?

谢谢.

-感谢您的评论!所以这是我想到的示例目录:

-- Thanks for the comment! So here is an example directory that I have in mind:

-MyFridge
 - MyFood.txt
  - MyApple.txt
  - MyOrange.txt
  - ...
 - MyDrinks
  - MySoda
    - MyDietCoke.txt
  - MyMilk.txt
  - ...
 - MyDesserts
 - MyIce
 ...

例如,我想将"My"替换为"Tom",并且我还想在所有文本文件中将"My"重命名为Tom.我可以使用node-fs-extra将目录复制到其他位置,但是我很难重命名文件名.

I want to replace "My" with "Tom," for instance, and I also would like to rename "My" to Tom in all the text files. I am able to copy the directory to a different location using node-fs-extra, but I am having a hard time with renaming the file names.

推荐答案

定义自己的工具

const fs = require('fs');
const path = require('path');


function renameFilesRecursive(dir, from, to) {

   fs.readdirSync(dir).forEach(it => {
     const itsPath = path.resolve(dir, it);
     const itsStat = fs.statSync(itsPath);

     if (itsPath.search(from) > -1) {
       fs.renameSync(itsPath, itsPath.replace(from, to))
     }

     if (itsStat.isDirectory()) {     
       renameFilesRecursive(itsPath.replace(from, to), from, to)
     } 
   })
}

用法

const dir = path.resolve(__dirname, 'src/app');

renameFilesRecursive(dir, /^My/, 'Tom');

renameFilesRecursive(dir, /\.txt$/, '.class');

这篇关于NodeJS-递归复制并重命名现有目录中的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆