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


#1

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’.

http://puu.sh/h91vy/f511ca93d2.png
(etc)

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


#2

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.


#3

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!
#4

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?


#5

I think that’s right


#6

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


#7

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