What is the difference between fs.writeFile and fs.writeFileSync

fs.writeFile:

fs.writeFile allows you to create a file and pass data at creation time.This function takes 3 parameters and an optional parameter.

  • file
  • data
  • options (optional)
  • callback

The first parameter is a path ending with filename or file descriptor. Second parameter stores data that is going to be put in the file. Third parameter is a callback function that will be called when fs.writeFile is either done or failed.

Optional parameter can be used to change the default values of encoding, mod, and flag of the file. By default they are set to:

  • encoding: 'utf8'
  • mode: 0o666
  • flag: 'w'.

Below is an example of fs.writeFile.

var fs = require(‘file-system’);
fs.writeFile(‘C:/Users/aguled2/Desktop/fs/test.txt’, ‘abdi’, function(err) {
console.log(err);
});

fs.writeFileSync:

fs.writeFileSync also allows you to create a file and add data. But this function takes 2 parameters and an optional parameter.

  • file
  • data
  • options (optional)

All the parameters are the same as fs.writeFile. The only difference is that this function doesn’t take a callback function. Without the callback it blocks the main thread which causes no delays in the program execution.

Below is an example of fs.writeFileSync.

var fs = require(‘file-system’);
fs.writeFileSync(‘C:/Users/aguled2/Desktop/fs/test.txt’, “abdi g”, function(err){ console.log(err);
})