'Error removing directory which is not empty

I'm trying to delete a directory when all the tests finish with an after, and I get the following error:

fs.rmdir is not a function

Here is mi code:

after(() => {
        const fs = require('fs');
        const dir = '../../../../../../downloads';
        
        fs.rmdir(dir, { recursive: true }, (err) => {
            if (err) {
                throw err;
            }
        });
    })


Solution 1:[1]

Seems like the recursive option is deprecated from Node.js 14.14.0 (what version do you use?), so you can now use:

fs.rm(dir, { recursive: true, force: true }, (err) => {
  if (err) {
    throw err;
  }
});

Solution 2:[2]

The reason is fs is a Node library, but you are trying to use it in the browser.

For Node code, use a task

/cypress/plugins/index.js

const fs = require('f')

module.exports = (on, config) => {
  on('task', {
    clearDownloads(message) {
      const fs = require('fs');
      const dir = '../../../../../../downloads';
        
      fs.rm(dir, { recursive: true }, (err) => {
        if (err) {
          throw err;
        }
      });
      return null
    },
  })
}

But there's a couple of configuration items that seem to do this job for you

Ref Configuration - Downloads

downloadsFolder - Path to folder where files downloaded during a test are saved

trashAssetsBeforeRuns - Whether Cypress will trash assets within the downloadsFolder, screenshotsFolder, and videosFolder before tests run with cypress run.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pavelsaman
Solution 2 Fody