Cypress:如何读取文本文件,但即使文件不存在也继续执行?

dus*_*kin 0 javascript typescript cypress

我想写入一个文本文件,但如果它已经存在,我想先清理它。

如果它不存在,我想创建它并开始写入它。

我多次尝试清除文件(如果文件存在),但如果不存在则继续执行,但是该方法

cy.readFile() 
Run Code Online (Sandbox Code Playgroud)

如果找不到文件,我的执行总是会崩溃。

例如:

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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在文件不存在的情况下 - catch 没有达到我的意思。

请指教。

小智 5

无需清理文件 -cy.writeFile()将覆盖它!

如果您只调用cy.writeFile(newData),则文件中不会保留任何旧数据。它只会覆盖以前的内容。

这就是为什么有一个附加选项的原因

将内容附加到文件末尾

cy.writeFile('path/to/message.txt', 'Hello World', { flag: 'a+' })
Run Code Online (Sandbox Code Playgroud)