Make objects with node.js

Node.js is definitely awesome, especially on an i/o heavy application.
Being a Java developer, my first take was on making a class.
ResultExtractor.js would be the file used to define a module.

function ResultExtractor(wordToMatch) {
    this.wordToMatch = wordToMatch
}

ResultExtractor.prototype.filterRecords = function(jsonResults) {
    var filteredRecords = []

    for(var i=0;i<jsonResults.length;i++) {
        var jsonResult = jsonResults[i]
        if(this.recordContains(jsonResult))
            filteredRecords.push(jsonResult)
    }

    return filteredRecords
}

ResultExtractor.prototype.recordContains = function(jsonResult) {
    return jsonResult['word'].indexOf(this.wordToMatch)!=-1;
}

module.exports = ResultExtractor

On your other file that imports the module you can use the ResultExtractor class


var ResultExtractor = require('./ResultExtractor')

var resultExtractor = new ResultExtractor('whatever')
var testData = [{'word':'whatever'},{'word':'where'},{'word':'when'}]
var filteredData = resultExtractor.filterRecords(testData)

console.log(filteredData)

That’s it!!! More post will follow, node.js seems really promising.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s