首页 > 解决方案 > 如何避免使用 fs-extra.copySync 方法复制 .txt 和 .xml 文件类型

问题描述

我正在做一个打字稿的小任务,目前我正面临下面提到的问题,我无法找到实现这一目标的方法。任何关于下面提到的问题的指导或建议将不胜感激。

我有一个小任务将目录复制到文件系统中的另一个位置,所以目前我在 npm 包中使用 fs-extra.copySync 方法,将目录从一个位置复制到另一个位置,但是当我复制文件时需要排除一些文件类型(.xml、.txt)。

所以问题出在我要复制的目录中,如果有一个子文件夹,那么不允许的文件类型(.xml 和 .txt)也会被复制。所以我尝试了以下方法,但它给出了以下错误。

无法读取 null 的属性“readFiles”

我尝试的方法如下所述。

服务器.ts

function moveFilesAll()
{
   var moveFrom = "./src";
   var moveTo = "./Destination";

   readFiles(moveFrom,moveTo);
} 

    function readFiles(moveFrom,moveTo)
    {
      fs.readdir(moveFrom, function (err, files) {
        if (err) {
          console.error("Could not list the directory.", err);
          process.exit(1);
        }


      files.forEach(function (file, index) {

        console.log(file + " "+ index)
        // Make one pass and make the file complete
        var fromPath = path.join(moveFrom, file);
        var toPath = path.join(moveTo, file);

        fs.stat(fromPath, function (error, stat) {
          if (error) {
            console.error("Error stating file.", error);
            return;
          }

          if (stat.isFile())
          {

            console.log("'%s' is a file.", fromPath);
            console.log(path.extname(fromPath));
             //files get copying here
          if(path.extname(fromPath) =='.txt' || path.extname(fromPath) == '.xml' ||  path.extname(fromPath) == '.config'){
            console.log("Unallowed file types");
          }
          else
          {
            console.log("---------------Files copying--------------------------");
                fsExtra.copySync(fromPath, toPath);
                console.log("copied from '%s' to '%s'. ", fromPath, toPath); 
          }




          }
            else if (stat.isDirectory())
          {
            console.log("=================Directory=============");
            console.log("From path "+fromPath);
            console.log("TO path "+toPath);
            readFiles(fromPath,toPath);
            console.log("'%s' is a directory.", fromPath);
          } 
        });

    })
      })
    }

标签: typescriptnpmfs-extra

解决方案


您可以使用支持 glob-pattern 的库,例如copy

npm i --save copy
npm i --save-dev @types/copy

然后像这样使用它。

// Creates the glob pattern for exluded files, result looks like this: '*.xml|*.txt'
const excludedFilesGlob:Array<string> = ['xml', 'txt']
   .map(ft => `*.${ft}`)
   .join('|');

// The source glob, include all files except for the excluded file types
const source:string = `./src/**/!(${exludedFileTypes})`;
const destination:string = './Destination';

copy(source, destination, (err, files) => {
  // This callback is called when either an error occured or all files were copied successfully
  if (err) throw err;
  // `files` is an array of the files that were copied
});

推荐阅读