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

When compiling TypeScript, the exported module cannot be located

I've encountered an issue while working on my TypeScript project. Upon compiling my code with the following configuration: { "compilerOptions": { "target": "ESNext", "module": "ESNext", & ...

Notify using slack when a Firebase Cloud Functions deployment event occurs

Is there a way to automatically send a Slack message every time a deployment occurs on Firebase Cloud Functions? The message should include the project ID, functions that were deployed, and any deployment messages. I am proficient in sending Slack message ...

Tips for addressing the browser global object in TypeScript when it is located within a separate namespace with the identical name

Currently diving into TypeScript and trying to figure out how to reference the global Math namespace within another namespace named Math. Here's a snippet of what I'm working with: namespace THREE { namespace Math { export function p ...

Unable to execute the npm run dev command

How can I start this React app? I tried using npm run dev An error occurred: npm run dev > [email protected] dev > cross-env NODE_ENV=development npm-run-all -p api client:dev server:dev styles:w ... Error: Node Sass does not yet support y ...

Is there a way to execute a script during every npm install process?

Is it possible to set up pre-push hooks for Git with each npm install action? Are there any alternative solutions that do not involve installing tools like Gulp, and instead rely solely on npm? ...

Detecting Typescript linting issues in VSCode using Yarn version 3.2.3

Every time I try to set up a new react or next app using the latest yarn v3.2.3, my VS Code keeps showing linting errors as seen in the screenshot below. The main error it displays is ts(2307), which says Cannot find module 'next' or its correspo ...

Setting up a ts-node project with ECMAScript modules. Issue: Unrecognized file extension ".ts"

I am currently in the process of setting up a minimalistic repository that incorporates ts-node and ESM for a project. Despite the existence of previous inquiries on this topic, I have encountered numerous outdated responses. Even recent answers appear to ...

It appears that Nodemon has stopped functioning correctly. To use Nodemon, simply input the following command: nodemon [nodemon options]

nodemon has always been reliable for me. I used to run nodemon server and it would automatically watch for updates and restart the server file. However, lately when I try to do this on my Windows cmd, I get the following message: Usage: nodemon [nodemon o ...

The RxJS race function comes to a standstill if neither stream completes

Consider the code snippet below: import { interval, race, Subject } from 'rxjs'; import { mapTo } from 'rxjs/operators'; const a$ = new Subject<number>(); const b$ = interval(1000).pipe(mapTo(1)); race([a$, b$]).subscribe(consol ...

Warning: npm will attempt to retry the connection, but encountered an error on the last attempt due to a connection refusal

After creating an Asp.Net core application, I encountered an error when running the command npm install. The error message said: npm WARN retry will retry, error on last attempt: Error: connect ECONNREFUSED I am unsure about what might be causing this ...

Gulp 4 functions not executing in sync with parallel/series operations

My build process involves gathering all deployable files and zipping them. An issue arises when using gulp.parallel or gulp.series. It appears to not wait even with callbacks and returns in place. I have attempted using run-sequence and running other fu ...

Error message stating: "Failed to locate module ' node-darwin-arm64/package.json' on M1 Chip while running NPM Install."

I have noticed that various versions of this question have been raised before, but I haven't come across a solution that doesn't involve using Rosetta or manipulating the architecture with zsh. I prefer to use bash and would like to avoid dealing ...

Facing Syntax Errors When Running Ng Serve with Ngrx

Currently, I am enrolled in an Angular course to gain proficiency in ngrx. In a couple of months, I will be responsible for teaching it, so I am refreshing my memory on the concept. Strangely, even after installing it and ensuring my code is error-free, er ...

npm encountered an error while trying to install selenium-webdriver using the npm install command

My operating system is Windows Server 2008 R2 EE and I have the npm package manager installed. I am attempting to install the Selenium Webdriver package using the command below. Command: npm install selenium-webdriver However, when running this comma ...

Ensure the proper utilization of properties

Consider a scenario where I have a structure that defines a user along with their login and given name: export interface User { login: string; name: string; } Now, my objective is to make an API call using the user's login information: const fo ...

Guide to implementing a Page Object Model for improved debugging of Protractor tests

Introduction I am on a mission to streamline my e2e testing code using the Page Object Model for easier maintenance and debugging. My Approach When embarking on creating end-to-end tests with Protractor, I follow these steps to implement the Page Object ...

Issue with npm during installation of REACT - not functioning as expected

After executing all the necessary commands on the command line, including globally installing npm with npm install -g create-react-app, as well as running npx create-react-app <myprojectname> and clearing the npm cache, I consistently encountered an ...

Error: The function subscribe in _store_js__WEBPACK_IMPORTED_MODULE_12__.default is not supported

In my main App component, I am subscribing to the store in a normal manner: class App extends Component { constructor(props) { super(props) this.state = {} this.unsubscribe = store.subscribe(() => { console.log(store.getState()); ...

The CLI commands in Babel's Laravel have been shifted from the babel package to the babel-cli package

During my work in Laravel, I encountered an error while trying to execute the Gulp command: "Babel's CLI commands have been moved from the babel package to the babel-cli package". As I was upgrading to Laravel 5.3, I had to redo all the gulp tasks fo ...

Explaining the functionality of reserved words like 'delete' within a d.ts file is essential for understanding their

I am currently in the process of generating a d.ts file for codebooks.io, where I need to define the function delete as an exported top-level function. This is what my codebooks-js.d.ts file looks like at the moment: declare module "codehooks-js" ...