Synchronous File IO in Node.js
Posted by Dave Eddy on Mar 26 2013 - tags: techDoes calling
fs.writeFileSync
trigger a synchronous write to the file system?
If you are familiar with Node.js, or have at least heard of it, you’ve most likely heard that it uses non-blocking IO, and lets you do work asynchronously. One of the most basic APIs that Node provides is for the file system; With this API, you can read, write, remove, etc. files and do other file system related tasks and modifications.
This API follows a standard pattern of exposing 2 functions for each operation: one for asynchronous work, and the other for synchronous work. For example, if you want to read a file in Node you can do so asynchronously:
var fs = require('fs');
fs.readFile('/etc/passwd', function(err, buf) {
console.log(buf.toString());
});
Node will continue executing any javascript code it encounters while reading the file. Once all javascript is done being executed and the file is ready, it will run the anonymous function and print the file contents.