Un1
Un1

Reputation: 4132

Getting errors trying to create a new file using different methods with node fs in an Electron app

I'm trying to create a new file, but both of the methods below throw me an error:

method 1:

fs.writeFile(fullPath, '', (error) => { alert("exist") })

method 2:

if (!fs.existsSync(fullPath)) { 
  fs.appendFile(fullPath)
} else {     
  alert("exist")
}

Question:

What am I doing wrong?


Update:

I also tried this method suggested in the answer below:

// fullPath= 'C:/Users/Name/test.txt'

fs.writeFile(fullPath, '', (error) => {
  if(error) {
    alert("exist")
    return
  }
    alert("created")
})

and I get this:


Update 2:

I managed to make it work in a slightly different way:

if (!fs.existsSync(fullPath)) { 
  fs.writeFileSync(fullPath, '')
} else {
  alert("exist")
}

Upvotes: 0

Views: 108

Answers (1)

jens
jens

Reputation: 2145

For method 1, you are using fs.writeFile(file, data[, options], callback). So that callback will be called no matter what, alerting 'exists'. You should have a check, something like:

fs.writeFile(fullPath, '', (error) => {
  if(error) {
    alert("exist");
    return;
  }

  // no error, do what you want.
});

Reference: https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

For method 2, you are getting the warning because you are calling fs.appendFile without a callback. Either use fs.appendFileSync or give it a callback.

Reference: https://nodejs.org/api/fs.html#fs_fs_appendfile_file_data_options_callback

Upvotes: 2

Related Questions