Al guardar un archivo con la API de acceso al sistema de archivos, si se produce un error entre escribir y guardar un archivo nuevo, se sigue creando y guardando un archivo.
¿Hay alguna forma de evitar que se cree y guarde este archivo?
Como ejemplo, con el siguiente código, se genera un error antes de que se ejecute la función de guardar. Este error impide que se ejecute la función de guardar; sin embargo, aún se crea un archivo.
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>todas las prevenciones se pueden crear a través de validaciones
Por ejemplo, cree una clase que valide los parámetros que requiere que se cumplan y, si la validación es correcta, ejecute la función de guardar.
Tu código ya está funcionando, solo moví las últimas líneas porque no son necesarias.
Probé tu código creando una carpeta que no puede crear archivos dentro
async function saveFile() { const options = { types: [{ description: 'Text File', accept: { 'text/plain': '.txt' }, }], excludeAcceptAllOption: true, } // here i make the changes try { fileHandle = await window.showSaveFilePicker(options); save(); } catch (err) { alert('failed') } }