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?

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
What kind of config needs to be available sync when probably all your code using those configs are async?
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.
-1

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
}

2 Comments

This is an naive argument. Check the async module or any promise implementation
You would probably still want to use promise all still on this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.