7

Everyone recommends using async (non-blocking) functions instead of sync functions in Node.js .

So whats the use of sync functions in node.js if they are not recommended?

For example : Why use fs.readFileSync() if fs.readFile() can do the same job without blocking?

Flake
  • 1,386
  • 17
  • 31
  • http://stackoverflow.com/questions/16336367/what-is-the-difference-between-synchronous-and-asynchronous-programming-in-node It's not that they're not reccomended, it's just a use case – Sterling Archer Nov 10 '15 at 18:35
  • Maybe a duplicate of http://stackoverflow.com/questions/31863621/synchronous-read-or-write-on-nodejs – skypjack Nov 10 '15 at 20:30

2 Answers2

11

Sync functions are useful, especially on startup, where you want to make sure that you have the result prior to executing any more code.

For example, you could load in a configuration file synchronously. However, if you are trying to do a file read during a live request, you should use async functions so you don't block other user requests.

TbWill4321
  • 8,626
  • 3
  • 27
  • 25
  • okay.....so from what I understand , sync functions not just block for that user but for others too . So a single blocking function can block the whole server from serving requests for that time? – Flake Nov 10 '15 at 18:41
  • That is correct. Node is single-threaded, so while one thing is happening, nothing else can. Using async functions let's the process go do other operations, then come back when it's finished. – TbWill4321 Nov 10 '15 at 18:43
  • 1
    What kind of config needs to be available sync when probably all your code using those configs are async? – Christiaan Westerbeek Nov 10 '15 at 18:54
  • 2
    For example, you may want to load a config file to get the port to run your server on. You would get that in a sync call, since you won't be doing any concurrent work until your server is up. – TbWill4321 Nov 10 '15 at 19:38
-2

Sometimes you want to execute code once you have finished reading or writing to a file. For example

function () {
    array.forEach(function(data) {
        fs.writeFile(data)
    });

    // do this after forEach has finished looping, not after files have finished being writen to
}

As apposed to:

function () {
    array.forEach(function(data) {
        fs.writeFileSync(data)
    });

    // do this after all files have been written to
}
Julien Vincent
  • 1,210
  • 3
  • 17
  • 40