Synchronous Function Calls
Now that I have spent nearly an entire chapter telling you how Node.js is very much asynchronous and about all the tricks and traps of programming nonblocking IO, I must mention that Node actually does have synchronous versions of some key APIs, most notably file APIs. You use them for writing command-line tools in Chapter 12, “Command-Line Programming.”
To demonstrate briefly here, you can rewrite the first script of this chapter as follows:
var fs = require('fs'); var handle = fs.openSync('info.txt', 'r'); var buf = new Buffer(100000); var read = fs.readSync(handle, buf, 0, 10000, null); console.log(buf.toString('utf8', 0, read)); fs.closeSync(handle);
As you work your way through this book, I hope you are able to see quite quickly that Node.js isn’t just for network or web applications. You can use it for everything from command-line utilities to prototyping to server management and more!