jprichardson / node-jsonfile

Easily read/write JSON files.
MIT License
1.2k stars 321 forks source link

writefile callback if no error? #29

Closed camillo777 closed 9 years ago

camillo777 commented 9 years ago

Hi! Do You know if the writefile function "callback" is called even on no error? I find it is called with "err" set to null. I do not understand if there was an error or not. I searched for it but it is not written anywhere. Thank you! Camillo

jprichardson commented 9 years ago

I'm not sure I understand your questions...

First...

Do You know if the writefile function "callback" is called even on no error?

Yes, as you indicate by this:

I find it is called with "err" set to null.

Could you post a snippet of what code you're running and your expected results/output?

camillo777 commented 9 years ago

Hi, to me it seems it is called even on success. Is it the correct behaviour of the function? Camillo

2015-07-02 12:20 GMT+02:00 JP Richardson notifications@github.com:

I'm not sure I understand your questions...

First...

Do You know if the writefile function "callback" is called even on no error?

Yes, as you indicate by this:

I find it is called with "err" set to null.

Could you post a snippet of what code you're running and your expected results/output?

— Reply to this email directly or view it on GitHub https://github.com/jprichardson/node-jsonfile/issues/29#issuecomment-117991704 .

jprichardson commented 9 years ago

to me it seems it is called even on success. Is it the correct behaviour of the function?

Yes. Consider this code:

var jsonFile = require('jsonfile')
var fs = require('fs')

var someFile = '/tmp/myfile.txt'
jsonFile.writeFile(someFile, {msg: 'hi'}, function (err) {
  if (err) console.error(err)
  // will output true
  console.log('2: ' + fs.existsSync(someFile))
})

// will output false
console.log('1: ' + fs.existsSync(someFile))

i.e. you need to write follow up code in the callback. If you don't, the file will may not have been written yet.