node.js – How to decide between fs.readFile(), fs.readFileSync(), and fsPromises.readFile()?
The difference between them has nothing to do with what types of files are being read, how many, what is done with the data, how to handle failures, etc. The differences are purely technical for the architecture in which the operation is being performed.
This is an asynchronous operation and will not block the code from continuing to the next operation. Follow-up actions for the completion of this operation are provided in a callback function as an argument to the operation.
This is a synchronous operation and will block the code from continuing to the next operation until this has completed. Follow-up code will just be after this operation like any other synchronous operation.
This is another asynchronous operation, but one which returns an awaitable Promise instead of accepting a callback as an argument. That Promise can be awaited directly, awaited at a later time, or followed up with .then() and .catch() operations like any other Promise.
If you absolutely must perform the operation synchronously then you’d have to use the second option above. That should be an exceedingly rare case and used only for good reason.
If you absolutely can’t use Promises then you’d want to use the first option above. Though it’s worth further exploring why that limitation is being imposed in the first place.
Barring any uncommon technical limitations or strict backward-compatability needs for legacy code, any new code should simply use the third option above.
Read more here: Source link
