Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get error `TypeError: fs.readdir is not a function` in Cypress

I wrote this code and it works fine that is written in TypeScript. When I use the same code in the test file in cypress I get error TypeError: fs.readdir is not a function

import * as fs from 'fs'

let inputPath: String = "C:\\Users\\rkon";
let replacementString = "/";
let newInputPath = inputPath.split('\\').join(replacementString)
console.log('path after replacement: ' + newInputPath);

fs.readdir(newInputPath as string, function (err: any, files: any[]) {
    //handling error
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    }
    //listing all files using forEach
    files.forEach(function (file) {
        console.log('file: ' + file);
    });
});

I verified the above code by first doing:

>tsc temp.ts
>node temp.js

As I said it worked fine but why does the same code not work in Cypress giving the following error:

TypeError: fs.readdir is not a function

like image 962
RajKon Avatar asked Mar 26 '26 12:03

RajKon


1 Answers

you can not use node modules within cypress because cypress executes test code in the browser. To use node modules, you must use tasks (which are executed in the node process) that are defined in the plugins file (important, because the plugins file is executed in the node context).

So you have to tell cypress in the cypress.json that you are using a plugins file:

{
    ...
    "pluginsFile": "cypress/plugins/plugins.js",
    ...
  }

Then define a task in plugins.js:

on('task', {
    readdir({ path }) {
      return fs.readdir(path, .....);
    }
  });

Use the task like this:

cy.task("readdir", { path: "..." }, { timeout: 30000 });
like image 189
Josef Biehler Avatar answered Mar 28 '26 02:03

Josef Biehler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!