使用 `ncp` 复制文件抛出:没有这样的文件或目录,mkdir

copying files using `ncp` throws: no such file or directory, mkdir

我正在使用 ncp 复制文件如下:

import ncp from "ncp";
import { promisify } from "util";

const ncpPromise = promisify(ncp);
const copyAssets = async (exportFolderName, includeSourceMaps) => {
  const assets = glob.sync("**/", { cwd: distPath });
  const options = { clobber: true, stopOnErr: true };
  if (!includeSourceMaps) {
    options.filter = (f) => {
      return !f.endsWith(".map");
    };
  }
  return Promise.all(
    assets.map((asset) => {
      return ncpPromise(
        path.join(distPath, asset),
        path.join(exportPath, exportFolderName, asset),
        options
      );
    })
  );
};

但这有时会失败并出现以下错误:

"ENOENT: no such file or directory, mkdir '/path/to/folder'"

我该如何解决这个问题?

我猜您正在尝试复制与给定 glob 匹配的所有文件,因此您需要执行以下操作:

const assets = glob.sync("**/*.*", { cwd: distPath }); // note the *.*

例如,您当前所讨论的 glob 将导致:

[
  'folder1/',
  'folder2/',
]

而这个答案中的 glob 将导致(这就是你想要的):

[
  'folder1/file1.txt',
  'folder1/file2.txt',
  'folder2/anotherfile.txt',
]

备选方案:

好像是ncp isn't being maintained. So, you can use fs-extra,也可以复制文件和目录:

const glob = require("glob");
const path = require("path");
const fs = require("fs-extra");

const copyAssets = async (exportFolderName, includeSourceMaps) => {
  const assets = glob.sync("**/*.*", { cwd: distPath });

  const options = { overwrite: true };

  if (!includeSourceMaps) {
    options.filter = (f) => {
      return !f.endsWith(".map");
    };
  }

  return Promise.all(
    assets.map((asset) => {
      return fs
        .copy(
          path.join(distPath, asset),
          path.join(exportPath, exportFolderName, asset),
          options
        )
        .catch((e) => console.log(e));
    })
  );
};

NPM qir是的,是我自己发布的)是另一种选择:

const qir = require('qir');
qir.asyncing.copy('/A/path/to/src', '/B/path/to/dest')
    .then(() => { /* OK */ }
    .catch(ex => { /* Something wrong */ }
    ;

这里的/A/path/to/src可以是文件也可以是文件夹,不需要/B/path/to已经存在。

有一种同步方式:

const qir = require('qir');
qir.syncing.copy('/A/path/to/src', '/B/path/to/dest');

并且,如果 srcdest 都位于同一目录中:

const qir = require('qir');
let q = new qir.AsyncDir('/current/working/dir');
q.copy('A/path/to/src', 'B/path/to/dest')
    .then(() => { /* OK */ }
    .catch(ex => { /* Something wrong */ }
    ;

它会将/current/working/dir/A/path/to/src复制到/current/working/dir/B/path/to/dest.