Bamerza
Bamerza

Reputation: 1375

Returning a value derived from a NodeJS listener

I have a NodeJS readstream listener within a function and I am trying to get my function to return a value (contents of the file) which is derived from within the listener.

e.g. :

MyObj.prototype.read = function(){  

    var file3 = fs.createReadStream('test.txt', {encoding: 'utf8'});            
    var contentRead = '';       

    file3.addListener('data', function(data) {   
      contentRead += data.toString('utf-8');    
      return contentRead;            
    });
}

I would like to do something like var contents = myDerivedObj.read() to return the contents of the file.

However, the return from inside the listener is not getting returned correctly - getting 'undefined'. And, returning from outside the listener just returns an empty string.

I cannot change the signature of read(), so I cannot add a callback as an argument.

Upvotes: 1

Views: 988

Answers (1)

Femi
Femi

Reputation: 64700

In general, this is a poor pattern: NodeJS REALLY REALLY REALLY doesn't like it when you do things like this 'cause you block the main thread. You will discover that your performance TRULY sucks. So DON'T DO THIS. But if you MUST then you can try this:

MyObj.prototype.read = function(){  

    var file3 = fs.createReadStream('test.txt', {encoding: 'utf8'});            
    var contentRead = '';       
    var done = false;

    file3.addListener('data', function(data) {   
      contentRead += data.toString('utf-8');    
    });

    file3.addListener("end", function () {
       done = true;
     });

    while(!done);
    return contentRead;
}

EDIT: @Brandon is right, and I'm wrong. I just tested this and although I'd thought the callbacks would work the entire node process locks up. Do this:

MyObj.prototype.read = function(){      
        return fs.readFileSync('test.txt', 'utf-8');
    }

Upvotes: 3

Related Questions