使用 `ncp` 复制文件抛出:没有这样的文件或目录,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,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 没有得到维护。所以,你可以使用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,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