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
From here: https://docs.cypress.io/api/commands/readfile
If you attempt creating and writing to a file that already exists, the old file will be overwritten.
Generally,
cy.readFile()
andcy.writeFile()
should work for cypress. If it’s not, I think you’re usingcy.readFile()
for the purpose that is outside of yourcypress
framework. If that is the case then you should consider usingfs
module provided by node. If I have to write your requirement usingfs
module, it goes something like:Cypress has the documentation for that specific situation. Basically, they recommend the same approach as
@Eriks Klotins
does, but suggest to wrap it insidecy.task
: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