Async Series in NodeJS
When you need to do something in series with no dependency on carry over response from one to another NodeJS provides a wonderful asynchronous solution
/** * Created by krishnan on 5/4/15. */
var fs = require('fs'); var async = require('async'); var readFileCB = function(err, fileContent) { if(err) { console.log('Failed to read file'); } else { console.log('Contents of file\n'); console.log(fileContent); } } var readTextFile1 = function(fileName, cb) { fs.readFile(fileName, 'utf8', cb); } var readTextFile2 = function(fileName, cb) { fs.readFile(fileName, 'utf8', cb); } var readFile1Text = function(cb) { fs.readFile("file1.txt", 'utf8', cb); } var readFile2Text = function(cb) { fs.readFile("file2.txt", 'utf8', cb); } var workerReadFiles = [readFile1Text, readFile2Text]; async.series(workerReadFiles, readFileCB); //readTextFile("file1.txt", readFileCB);
Imagine a situation where results are dependent, like you need to read contents of a JSON file, load an object successfully, before you process to process JSON. That's where waterfall is extremely useful. One thing that you need to be aware here is, if any of the intermediate step fails, we do not move forward. In the following example, readJSONContent reads the local JSON file, if successfull, moves onto processJSON method.
/** * Created by krishnan on 5/4/15. */
var fs = require('fs'); var async = require('async') var readJSONContent = function(readCallBack) { console.log('Read invoked'); fs.readFile("customerForm.json", "utf8", function(err, fileContent){ if(err) { readCallBack(err, null); } else { readCallBack(null, fileContent); } }); } var processJSONContent = function(fileContent, processCallBack) { var customerContent = JSON.parse(fileContent); if(customerContent.firstName == "John") { processCallBack(null); } else { throw new Error("Wrong values in JSON"); processCallBack(null); } } var workflow = [readJSONContent, processJSONContent]; async.waterfall(workflow, function(error) { if(error) { console.log("Failed with error :" + error); } else { console.log('Finished reading ') } });
Event Emitters
Building a loosely coupled system with emitter. Emitters can be very useful as much as it can be abused to the core. (Concept is parallel to Notifications in iOS, if you have done some iOS programming). As much as the code is loosely coupled, I'd advice you take care when you do anything with events. Here's the sample code for the same/** * Created by krishnan on 5/4/15. */
var events = require('events'); var eventEmitter = new events.EventEmitter(); var startConnection = function() { console.log('Started connection to DB'); eventEmitter.emit('connection_success'); } var readData = function() { console.log('Read data from remote connection'); eventEmitter.emit('read_success'); } var connectionClosed = function() { console.log('Connection closed'); eventEmitter.emit('connection_closed'); } var allDone = function() { console.log('All done!!!'); } eventEmitter.on('connection', startConnection); eventEmitter.on('connection_success', readData); eventEmitter.on('read_success', connectionClosed); eventEmitter.on('connection_closed', allDone); eventEmitter.emit('connection');
We will be able to add more than one listener to an event through 'addListener' method of EventEmitter class. So can you remove one and all listeners through removeListener and removeAllListeners. You can set a upper limit on the number of listeners you can have on events through the method setMaxListeners
No comments:
Post a Comment