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

Upvotes: 0

Views: 623

Answers (2)

Fody
Fody

Reputation: 32044

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.

Upvotes: 0

pavelsaman
pavelsaman

Reputation: 8352

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

Upvotes: 1

Related Questions