Tips on preventing the copying of .txt and .xml files with the fs-extra.copySync function

Currently, I am working on a small TypeScript assignment and facing an issue that I can't seem to solve. Any guidance or advice on the problem mentioned below would be greatly appreciated.

The task at hand involves copying a directory from one location to another in the file system. I am utilizing the fs-extra.copySync method from the npm package to achieve this, however, I need to exclude certain file types (.xml, .txt) during the copy process.

The problem arises when there are sub-folders within the directory being copied, as the forbidden file types (.xml & .txt) also get copied along with them. I have tried different methods but encountered the following error:

Cannot read property 'readFiles' of null

The method I attempted is shown 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);
        } 
      });
    })
  })
}

Answer №1

If you're looking to implement glob-pattern support, consider using the library copy.

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

Here's how you can utilize it:

// Creating a glob pattern for excluded files - resulting in '*.xml|*.txt'
const excludedFilesGlob:Array<string> = ['xml', 'txt']
   .map(fileType => `*.${fileType}`)
   .join('|');

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

copy(source, destination, (error, copiedFiles) => {
  // Handle any errors or process the array of successfully copied files
  if (error) throw error;
  // `copiedFiles` contains the list of files that were successfully copied
});

Answer №2


const sourceDirectory = '/path/to/source/directory'
const destinationDirectory = '/path/to/destination/directory'

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

fs.copySync(sourceDirectory, destinationDirectory, { filter: fileFilter })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible that a declaration file for module 'material-ui/styles/MuiThemeProvider' is missing?

I have been trying to implement the react material-ui theme after installing it via npm. However, I am encountering errors when adding 'import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";' in boot-client.tsx: TS7016: Could not ...

The error message that is popping up on Windows when running `npm start` is

Hey there! I'm having an issue with my Windows 10 installation and Mean. After installing express, I tried to start npm using the command "npm start" but encountered the following error: C:\>npm start npm ERR! Windows_NT 6.3.9600 npm ERR! arg ...

Unable to locate a type definition file for module 'vue-xxx'

I keep encountering an error whenever I attempt to add a 3rd party Vue.js library to my project: Could not find a declaration file for module 'vue-xxx' Libraries like 'vue-treeselect', 'vue-select', and 'vue-multiselect ...

The element is implicitly assigned an 'any' type as the expression of type 'any' cannot be used to index a type with createStyles

My stylesheet looks like this: const badgeStyle = createStyles({ badge: { borderRadius: "12px", padding: "5px 12px", textTransform: "uppercase", fontSize: "10px", fontWeight: 700, lineHeight ...

What makes TypeScript believe that the variable could possibly be undefined when it is clearly not the case?

I recently encountered an issue where TypeScript incorrectly identifies a variable as possibly being undefined. Here is a simplified example: const func = (val1?: boolean, val2?: boolean) => { if (!val1 && !val2) return; let result: boolean; ...

When logging `self`, the output field is present; however, attempting to log `self.output` results in

I've encountered a strange issue. When I use console.log(self) to log the variable, it shows that the output key is set and contains all the values. However, if I try to log console.log(self.output), it returns undefined. Does anyone know why this is ...

The OpenShift alpine node image is experiencing issues with npm functionality

I've encountered a strange issue with my deployment in OpenShift. When I build the image locally and then push it to the registry before taking it to OCP, everything runs smoothly. However, when I use a CI process in Azure Pipelines to build and push ...

Issue TS2365: The operation of addition cannot be performed between an array of numbers and the value -1000

I'm encountering an error in my ng serve logs despite the function functioning properly with no issues. However, I am concerned as this may pose a problem when building for production. How can I resolve this error? uuidv4() { return ([1e7]+-1e3+- ...

MERN application encounters error with running "heroku-postbuild" script during deployment on Heroku platform

During the process of deploying my app to Heroku, everything seems to be running smoothly until I encounter an issue. After logging in, I execute a series of terminal commands for deployment and receive the following responses: heroku login heroku: Press a ...

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

Npm is experiencing a technical issue

Encountering a serious issue with npm, I am facing difficulty in installing APIs like bluebird or fs due to an error message being thrown by npm. npm install bluebird -g npm WARN npm npm does not support Node.js v0.8.20 npm WARN npm You should probably up ...

Determining the function return type by analyzing an array of functions

If you have a vanilla JavaScript function that accepts an array of callbacks (each returning an object) and combines their outputs, how can TypeScript be used to determine the return type of this function? While ReturnType is typically used for a single ...

The Azure GraphQL serverless function encountering an issue with the Cosmos DB connection, displaying an

After developing a serverless GraphQL API function using Azure functions and connecting it to Cosmos DB, I have encountered an issue with "Invalid URL" that has been puzzling me for a week. Despite running the graphql function locally without any problems, ...

Running 'npm run dev' on SiteGround server can be done by accessing the command line interface and navigating to the

I have been working on a Laravel website and now I am in the process of hosting it. A friend recommended SiteGround to me, so I purchased a plan from them for a year. I have successfully uploaded and configured my files to connect to the database correctly ...

Encountering Issues While Trying to Install Node-Mapnik on Windows 8.1 64-bit Operating System

I keep encountering an error message every time I attempt to install node-mapnik on my Windows 8.1 x64 computer. npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\&bs ...

NodeJS and TypeScript are throwing an error with code TS2339, stating that the property 'timeOrigin' is not found on the type 'Performance'

I am currently working on a NodeJS/TypeScript application that utilizes Selenium WebDriver. Here is an excerpt from the code: import { WebDriver } from "selenium-webdriver"; export class MyClass { public async getTimeOrigin(driver: WebDriver ...

Is it possible in Angular to generate a module and component without including a CSS file in a single command?

Is it possible to generate a Module linked to a component without automatically creating a css file? For example, the default method I've been using involves: ng generate module name / ng generate component name This results in the typical componen ...

Adding custom CSS and JavaScript to an Angular 4 project can be done by including the necessary

When working with Angular 2, I was able to include stylesheets directly in the index.html like so: <link rel="stylesheet" href="css/mycss.css"> However, with Angular 4, the styles need to be added to the angular-cli.json file within the styles and ...

All authentication logic in Angular encapsulated within the service

I am considering moving all the business logic into the auth service and simply calling the method on the component side. Since none of my functions return anything, I wonder if it's okay or if they will hang. COMPONENT credentials: Credentials = ...

Incorporate an external library

I am currently facing a challenge in my angular2 project where I need to import a 3rd party library. Here are the steps I have taken so far: ng new myproject npm install --save createjs-easeljs npm install @types/easeljs However, I am stuck at this poin ...