Untitled

mail@pastecode.io avatar
unknown
javascript
25 days ago
1.0 kB
5
Indexable
Never
var fs = require('fs');
var cache = {};

function myPowerfulRead(filename, callback) {
    if (cache[filename]) {
        callback(cache[filename]);
    } else {
        fs.readFile(filename, 'utf8', function (err, data) {
            cache[filename] = data;
            callback(data);
        });
    }
}

function createFileReader(filename) {
    var listeners = [];
    myPowerfulRead(filename, function (value) {
        listeners.forEach(function (listener) {
            listener(value);
        });
    });
    return {
        onDataReady: function (listener) {
            listeners.push(listener);
        }
    }
}

var reader1 = createFileReader('data.txt');
reader1.onDataReady(function (data) {
    console.log('First call data: ' + data);

    //...sometime later we try to read again from
    //the same file
    var reader2 = createFileReader('data.txt');
    reader2.onDataReady(function (data) {
        console.log('Second call data: ' + data);
    });
});
Leave a Comment