path must be a string or Buffer on console: node.js (electron)

0

I'm developing an application on electron, and one of my functions is to backup a json.

When I open the ('fs') dialog box and save the file, I get no error in the console.

When I open the dialog box and cancel the operation (do not save the file) I get an error in the console:

Uncaught TypeError: path must be a string or Buffer
    at Object.fs.open (fs.js:549:11)
    at Object.module.(anonymous function) [as open] (ELECTRON_ASAR.js:200:20)
    at Object.fs.writeFile (fs.js:1211:6)
    at dialog.showSaveDialog (file:///C:/Users/Daniel/Documents/vendas-electron/app.js:63:10)
    at CallbacksRegistry.apply (C:\Users\Daniel\Documents\vendas-electron\node_modules\electron\dist\resources\electron.asar\common\api\callbacks-registry.js:48:42)
    at EventEmitter.<anonymous> (C:\Users\Daniel\Documents\vendas-electron\node_modules\electron\dist\resources\electron.asar\renderer\api\remote.js:299:21)
    at emitThree (events.js:116:13)
    at EventEmitter.emit (events.js:194:7)

My backup role is this. What might be causing this error?

function backUp() {
  /* a) pega a data atual formatada */
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth()+1;
  var yyyy = today.getFullYear();
  if(dd<10){
      dd='0'+dd;
  }
  if(mm<10){
      mm='0'+mm;
  }
  var today = yyyy+'-'+mm+'-'+dd;
  /* FIM a) */

  var read = require('read-file-utf8') // Ler arquivos
  var dialog = remote.dialog // Carrega os dialogos do sistema
  var fs = require('fs'); // Carrega o File System (CRUD)
  const fileExists = require('file-exists')
  var check = fileExists.sync(__dirname+'/db.json')
  var data = {}
  if(check == true){
    data = read(__dirname+'/db.json')
    dialog.showSaveDialog({title: 'Backup do banco de dados',defaultPath: '.\backup' + today +'.json'},(fileName) => {
      fs.writeFile(fileName, data, (err) => {
        if(err) console.log(err); // não é esta linha
        alert('O backup foi realizado com sucesso')
      })
    })
  } else{
    alert('Não há banco de dados para salvar.')
  }
}
    
asked by anonymous 19.07.2017 / 11:33

1 answer

0

The error occurs because the command fs.writeFile(fileName, data, (err) => { requires that fileName is a valid path, in case the action is being canceled, it does not pass a valid path.

You can avoid this by validating the path before sending to fs.writeFile

    
03.10.2017 / 05:35