When saving a file using the File System Access API, if an error occurs between writing to and saving a new file, a file is still created and saved.
Is there a way to prevent this file from being created and saved?
As an example using the following code, an error is thrown before the save function is ran. This error prevents the save function from running; however, a file is still created.
let fileHandle;
async function save() {
let stream = await fileHandle.createWritable();
await stream.write();
await stream.close();
}
async function saveFile() {
const options = {
types: [{
description: 'Text File',
accept: {
'text/plain': '.txt'
},
}],
excludeAcceptAllOption: true,
}
try {
fileHandle = await window.showSaveFilePicker(options);
} catch (err) {
return;
}
throw "Some error occurs, preventing the 'save' function from being reached...";
save();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>File System Access Test</title>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<button type="button" onclick="saveFile()">Save File</button>
</body>
</html>