Is the try-catch-finally block synchronous in node.js?

krb686 picture krb686 · Jul 10, 2013 · Viewed 19.5k times · Source

I have some code runing in a child process in a node program like so:

try{
    var data = fs.readFileSync(urlPath, {"encoding":"utf8"});
} catch (err) {
    console.log("Error reading url file...");
    throw err;
} finally {
    console.log("File read!");
    var array = data.split("\n");

    console.log("Found " + array.length + " urls");

This code is called from another node program, that needs to wait until all the operations in this file are done. Unfortunately, the child process is exiting with code 0 before any of the code under the finally block is executed.

This is leading me to believe even the try-catch-finally is asynchronous. Is that correct?

Answer

SLaks picture SLaks · Jul 10, 2013

Your question is confusingly worded.

The entire Javascript language is fully synchronous; all language constructs, including catch and finally blocks, will execute synchronously before running the next line of code.

However, they are not aware of any asynchronous operations that may have begun, and will not wait for them to finish.