Difference between fs functions and fs functions ending with 'sync'


While trying to figure out how to manipulate the filesystem, I found that the ‘fs’ module has a bunch of methods and the same methods with the suffix ‘Sync’.


What is the difference between them? The only difference I can spot (between trying both), is that only the Sync ones work.

Also, secondary question, I found stuff about exists being deprecated and replaced with access. Is this still happening? Exists is working for me right now, without a deprecation method.

Tertiary question, readFileSync seems to return a Buffer object with a bunch of bytes in it. What’s the best way to convert that to a string (or just read a string out of the file in the first place)?
EDIT: Found the answer later, toString


Sync is synchronous and blocks execution until finished. These return their results as return values.

The others are asynchronous and return immediately while they function in the background. You pass a callback function which get called when they finish.


The *Sync variants are synchronous functions, and they immediately return a value, while the others are asynchronous, returning undefined, but accepting a callback to handle their response.

# synchronous
data = fs.readFileSync filename
# i can use the data variable now:
console.log data

# asynchronous
fs.readFile filename, (err, data2) ->
  # now the data variable is available in the callback context,
  # but not in the context the fs.readFile function was called
  console.log data2

While it may look attractive to use the synchronous variants for ease of programming, they are blocking functions, meaning that while they are being executed (reading files etc.) the node process must wait for them to return a value and can’t do anything else.

Getting stdout from BufferedProcess is very slow for ~15K lines!

Aha, I expected it to be something to do with synchronicity. I usually expect to see function (synchronous) and functionAsync (asynchronous, of course) rather than function (async) and functionSync. Is there any reason they were made this way rather than the other way? Because it encourages asynchronicity?


I think that’s right


Well, not just encouraging to use them, but also the fact that you use the async functions more often


And the fact that most functions in the Node world are async.