Everyone remends 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 remended?
For example : Why use fs.readFileSync()
if fs.readFile()
can do the same job without blocking?
Everyone remends 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 remended?
For example : Why use fs.readFileSync()
if fs.readFile()
can do the same job without blocking?
- stackoverflow./questions/16336367/… It's not that they're not recended, it's just a use case – Sterling Archer Commented Nov 10, 2015 at 18:35
- Maybe a duplicate of stackoverflow./questions/31863621/… – skypjack Commented Nov 10, 2015 at 20:30
2 Answers
Reset to default 11Sync 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.
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
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742355989a4428444.html
评论列表(0条)