JavaScript is a single threaded programming language (can do one task at the time)
So it first runs the main thread (synchronous) then executes asynchronous tasks in the event loop (this is how I understood but apparently I'm wrong)
Node.js uses libuv a library which handles asynchronous tasks
// synchronously open file descriptor var fd = fs.openSync('testFile', 'r+'); // synchronously write data to the file fs.writeSync(fd, ' first data part '); // asynchronously write data to the file fs.write(fd, ' second data part ', function(err){ if(err) console.log( err ); }); // asynchronously close the file descriptor fs.closeSync(fd); The asynchronous write method successfully writes the data to the file, BUT NOT always! (method throws an error of 'bad file descriptor')
I expected an error by the asynchronous 'write()' method because the file descriptor is closed synchronously so it shouldn't have a valid file descriptor to work with (but it's not the case at least not always)
Here are questions
Does that mean that asynchronous tasks are executed separately by libuv running a separate JS thread so this causes the above example not to crash?
If I'm right above is this the same behavior in the browser (is there any asynchronous difference between browsers?)
If I'm wrong how the hell the above asynchronous 'write()' method gets the file descriptor?