簡體   English   中英

使用 `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 *.*

例如,您當前的問題將導致:

[
  '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, 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM