NodeJS - 递归复制和重命名现有目录中的所有内容

3
我有一个包含文件夹和文件的目录。我想要将整个目录及其所有内容复制到另一个位置,并将所有文件重命名为更有意义的名称。我想使用nodejs完成这一系列操作。有没有一种简单的方式来完成这个任务,而不是逐个移动并逐个重命名?
谢谢。
-- 感谢您的留言!以下是我考虑的示例目录:
-MyFridge
 - MyFood.txt
  - MyApple.txt
  - MyOrange.txt
  - ...
 - MyDrinks
  - MySoda
    - MyDietCoke.txt
  - MyMilk.txt
  - ...
 - MyDesserts
 - MyIce
 ...

比如说,我想将“我的”替换为“汤姆”,并且我还想在所有文本文件中将“我的”重命名为汤姆。我可以使用node-fs-extra将目录复制到另一个位置,但是我在重命名文件名方面遇到了困难。


1
你应该发布一个示例文件层次结构,以便我们可以看到你所想的新文件名映射。 - srquinn
1
谢谢!我已经编辑了帖子,提供了一个例子。 - user3294556
从walk和fs库开始,然后继续前进。 - Jake Sellers
2个回答

6

定义你自己的工具

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');

在上面的例子中,'from'和'to'参数没有像这样在递归调用中传递:renameFilesRecursive(itsPath, from, to)。 - Niels Boogaard
1
@NielsBoogaard 如何将重命名后的文件放入一个新文件夹中? - mesqueeb
什么是将任何文件名重命名为i.txt的正则表达式?例如:a_1.txt,22.txt,b.txt将变为1.txt,2.txt,3.txt。我知道对于I部分,我们需要一个计数器;这没关系,但如何检测文件呢?我尝试了/^.*\.txt$/但没有帮助。我得到了:错误:ENOENT:没有这样的文件或目录,重命名'/Images/1/10.jpg'->'/ImagesAll/0.jpg' - Dr.jacky

0

fs-jetpack有一个非常好的API来处理这样的问题...

const jetpack = require("fs-jetpack");

// Create two fs-jetpack contexts that point 
// to source and destination directories.
const src = jetpack.cwd("path/to/source/folder");
const dst = jetpack.cwd("path/to/destination");

// List all files (recursively) in the source directory.
src.find().forEach(path => {
  const content = src.read(path, "buffer");
  // Transform the path however you need...
  const transformedPath = path.replace("My", "Tom");
  // Write the file content under new name in the destination directory.
  dst.write(transformedPath, content);
});

您可以通过添加更多关于代码的信息以及如何帮助 OP 来改善您的回答。 - Tyler2P
@Tyler2P,这是给你的。 - Jakub Szwacz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接