0

我正在使用 fs-extra 的复制方法将文件从源复制到目标。我的用例是创建文件的副本,其名称类似于目标中是否存在同名文件。fs-extra 模块的复制方法会覆盖目标文件。

4

2 回答 2

1

你可以尝试这样的事情:

const fs = require('fs-extra');

async function copy(src, dest) {
  try {
    await fs.copy(src, dest, { overwrite: false, errorOnExist: true });
    return true;
  } catch (error) {
    if (error.message.includes('already exists')) {
      return false;
    }
    throw error;
  }
}

async function copyWithoutOverwrite(src, dest, maxAttempts) {    
  try {
    if (!await copy(src, dest)); {
      for (let i = 1; i <= maxAttempts; i++) {
        if (await copy(src, `${dest}_copy${i}`)) {
          return;
        }
      }
    }
  } catch (error) {
    console.error(error);
  }
}

const src = '/tmp/testfile';
const dest = '/tmp/mynewfile';
const maxAttempts = 10;

copyWithoutOverwrite(src, dest, maxAttempts);
于 2018-07-04T08:53:33.900 回答
0

所以基本上你需要实现自定义复制过程,你可以随时中断和改变。fs-jetpack在这方面做得很好。

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

const src = jetpack.cwd("path/to/source/folder");
const dst = jetpack.cwd("path/to/destination/folder");

const findUnusedPath = path => {
  const pathDir = pathUtil.dirname(path);
  const extension = pathUtil.extname(path);
  const fileName = pathUtil.basename(path, extension);
  const pathCandidate = pathUtil.join(pathDir, `${fileName}-duplicate${extension}`);

  if (dst.exists(pathCandidate)) {
    // Will just add "-duplicate-duplicate-duplicate..." to name 
    // of the file until finds unused name.
    return findUnusedPath(pathCandidate);
  } else {
    return pathCandidate;
  }
};

// Iterate over all files in source directory and manually decide 
// where to put them in destination directory.
src.find().forEach(filePath => {
  const content = src.read(filePath, "buffer");
  let destPath = filePath;
  if (dst.exists(destPath)) {
    destPath = findUnusedPath(destPath);
  }
  dst.write(destPath, content);
});

这里使用文件读/写而不是复制,因为在这种特殊情况下它更快。复制需要先检查路径是什么:目录或文件。如果我们已经知道它是一个文件,则无需进行此额外工作。

于 2021-12-02T12:34:01.287 回答