Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fs.writeFile() doesn't return callback

I'm trying to write a file with the users authentication data to the disk. To achieve this I wrote the following function:

function writeAuthFile(data, success, fail) {
  var fs = require('fs');
  fs.writeFile('auth.json', JSON.stringify(data), function(error) {
    if(error) { 
      console.log('[write auth]: ' + err);
        if (fail)
          fail(error);
    } else {
      console.log('[write auth]: success');
        if (success)
          success();
    }
  });
}

But it never calls the callback. I looked at the nodeJS docs for fs and it all seems to check out. Also all other asynchronous execution seems to have halted.

This is the first time I'm developing something serious in nodeJS so my experience in this environment is not that much.

like image 699
Feanaro Avatar asked Feb 16 '15 15:02

Feanaro


People also ask

Does fs writeFile overwrite?

fs. writeFileSync and fs. writeFile both overwrite the file by default. Therefore, we don't have to add any extra checks.

Is fs writeFile async?

The fsPromises. writeFile() method is used to asynchronously write the specified data to a file.

What is the difference between writeFileSync and writeFile?

writeFileSync() is a synchronous method & creates a new file if the specified file does not exist while fs. writeFile() is an asynchronous method.

Does fs writeFile create a file?

The fs. writeFileSync() creates a new file if the specified file does not exist.


1 Answers

Your code looks fine, I copy&paste and run it by simply calling writeAuthFile({test: 1});, file auth.json was created. So, mb error somewhere higher? add console.log after var fs = require('fs'); line and test.

like image 160
Daniel Avatar answered Oct 04 '22 03:10

Daniel