skip to Main Content

I want to write to a text file, but if it exists already, I’d like to clean it first.

If it does not exist, I want create it and start writing to it.

I made several attempts to clear the file in case it exists but also continue execution if it doesn’t, but the method

cy.readFile() 

always crashed my execution in case it didn’t find the file.

For example:

function clearFile(filePath) {
  try {
    // Read the contents of the file.
    const fileContents = cy.readFile(filePath, { encoding: "utf-8" });
  
    // If the file exists, clear it.
    if (fileContents) {
      cy.writeFile(filePath, "");
    }
  } catch (err) {
    // Ignore the error if the file does not exist.
    if (err.code === "ENOENT") {
      // The file does not exist.
    } else {
      // Rethrow the error if it is not a file not found error.
      throw err;
    }
  }
}

In the case file does not exist – catch is not being reached as I meant it would be.

Please advice.

4

Answers


  1. From here: https://docs.cypress.io/api/commands/readfile

    By default, cy.readFile() asserts that the file exists and will fail
    if it does not exist. It will retry reading the file if it does not
    initially exist until the file exists or the command times out.

    If you attempt creating and writing to a file that already exists, the old file will be overwritten.

    Login or Signup to reply.
  2. Generally, cy.readFile() and cy.writeFile() should work for cypress. If it’s not, I think you’re using cy.readFile() for the purpose that is outside of your cypress framework. If that is the case then you should consider using fs module provided by node. If I have to write your requirement using fs module, it goes something like:

    const fs = require('fs');
    
    function clearFile(filePath) {
      try {
        // Check if the file exists.
        fs.accessSync(filePath);
        
        // If the file exists, clear it.
        fs.writeFileSync(filePath, '');
      } catch (err) {
        // If the file does not exist, create it.
        if (err.code === 'ENOENT') {
          fs.writeFileSync(filePath, '');
        } else {
          // Rethrow the error if it is not a file not found error.
          throw err;
        }
      }
    }
    
    Login or Signup to reply.
  3. Cypress has the documentation for that specific situation. Basically, they recommend the same approach as @Eriks Klotins does, but suggest to wrap it inside cy.task:

    Read a file that might not exist

    Command cy.readFile() assumes the file exists. If you need to read a
    file that might not exist, use cy.task.

    // in test
    cy.task('readFileMaybe', 'my-file.txt').then((textOrNull) => { ... })
    
    
    // cypress.config.js
    const { defineConfig } = require('cypress')
    const fs = require('fs')
    
    module.exports = defineConfig({
      // setupNodeEvents can be defined in either
      // the e2e or component configuration
      e2e: {
        setupNodeEvents(on, config) {
          on('task', {
            readFileMaybe(filename) {
              if (fs.existsSync(filename)) {
                return fs.readFileSync(filename, 'utf8')
              }
    
              return null
            },
          })
        },
      },
    })
    
    Login or Signup to reply.
  4. There is no need to clean the file – cy.writeFile() will overwrite it!

    If you just call cy.writeFile(newData), none of the old data will remain in the file. It will simply overwrite the previous content.

    That’s why there’s an option to append

    Append contents to the end of a file

    cy.writeFile('path/to/message.txt', 'Hello World', { flag: 'a+' })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search