0

I've read and heard that I shouldn't return values in functions because it is a blocking operation and that it will potentially refuse any requests until the operation has finished.

So here's a small function I've coded and I'd like to know if I am handling it correctly. I'm saying this because I just started using node and I want to code in the correct way, also because it feels weird to have a testing condition inside the function and another one to test the callback.

function isWithinSplit(path, target, separator, callBack)
{
var response = "";
var readStream = fs.createReadStream(path);

readStream.on('data', function (data) {
    response += data;
});

//Data complete, process it
readStream.on('end', function (close) 
{
    var array = response.split(separator);

    for (var idx=0 ; idx < array.length; idx++)  
    {
        if(array[idx] != "" && array[idx] == target)
            callBack("true");
        else
            callBack("false");
    }
});

}

Call:

fileHelper.isWithinSplit(__dirname + ROOM_LIST_PATH, "hello", "|", function(data){
  if(data == "true")
    console.log("hurray!");
});

I just want to know if this is how people do and if it's efficient.

1 Answer 1

3

You forgot

  • error handling
  • using ===
  • caching array length
  • naming anonymous functions
function isWithinSplit(path, target, separator, callBack) {
    var response = "";
    var readStream = fs.createReadStream(path);

    readStream.on('data', function _aggregateData(data) {
        response += data;
    });

    //Data complete, process it
    readStream.on('end', function _findTarget(close) {
        var array = response.split(separator);

        for (var idx = 0, len = array.length; idx < len; idx++) {
            if (array[idx] === target) {
                return callBack(null, true);
            }
        }
        callback(null, false);
    });

    readStream.on('error', callBack);
}

fileHelper.isWithinSplit(__dirname + ROOM_LIST_PATH, "hello", "|", printIfSuccess);

function printIfSuccess(err, data) {
    if (data === true) {
        console.log("hurray!");
    }
}

You can also improve it using Array.prototype.any

readStream.on('end', function(close) {
    callback(null, response.split(seperator).any(function _doesItMatchTarget(val) {
        return val === target;
    }));
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.