Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

183
Visualizações
How can I prevent the File System Access API from saving file when an error occurs?

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>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

all preventions can be created through validations

For example create a class that validates the parameters that you require to be fulfilled and if the validation is correct then execute the save function.

about 4 years ago · Juan Pablo Isaza Relatório

0

Your code is already working, I only moved the last lines because they are unnecessary.

I tested your code creating a folder that cannot create files inside

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')
  }

}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda