0

I am working on a small assignment in typescript, currently I'm facing below mentioned issue and I was not able to figure out a way of achieving this.Any guidance or advises of below mentioned issue will be highly appreciated.

I have small task to copy a directory to another location in the file system,So currently I'm using fs-extra.copySync method in npm package, to copy directory from one location to another, but when I copy files need to exclude some file types (.xml, .txt).

So the issue is in the directory which I'm going to copy, if there's a sub folder the unallowed file types(.xml & .txt) will also get copied. So I tried below methods, but it's giving below error.

Cannot read property 'readFiles' of null

Methods I tried is mentioned below.

server.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);
          } 
        });

    })
      })
    }
siyumi_amarasinghe
  • 193
  • 1
  • 1
  • 13

2 Answers2

0

You can use a library with glob-pattern support for that, like copy.

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

Then use it like this.

// 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
});
pascalpuetz
  • 5,238
  • 1
  • 13
  • 26
0

const source = '/path/to/source/dir'
const destination = '/path/to/destination/dir'

const filter = file => {
  // get the file extension
  const ext = path.extname(file)
  
  // return true if the file is not a .txt or .xml file
  return ext !== '.txt' && ext !== '.xml'
}

fs.copySync(source, destination, { filter })
  • Please improve your answer. Check [How do I write a good answer](https://stackoverflow.com/help/how-to-answer) – Nullndr Dec 19 '22 at 07:38