Reputation: 4132
I'm trying to create a new file, but both of the methods below throw me an error:
fs.writeFile(fullPath, '', (error) => { alert("exist") })
exist
exist
AND creates the fileif (!fs.existsSync(fullPath)) {
fs.appendFile(fullPath)
} else {
alert("exist")
}
exist
DeprecationWarning: Calling an asynchronous function without callback is deprecated.
What am I doing wrong?
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:
created
created
AND creates the fileI managed to make it work in a slightly different way:
if (!fs.existsSync(fullPath)) {
fs.writeFileSync(fullPath, '')
} else {
alert("exist")
}
Upvotes: 0
Views: 108
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