1

i have a growing txt file and below function to read the file as it grows. This function i have put in a route js and invoking by $http call. Things are working but i don't know how to stop reading and terminate/cancel the function execution call. please help

var fs = require('fs'),
    bite_size = 256,
    readbytes = 0,
    file;

fs.open('test.txt', 'r', function(err, fd) {
    file = fd; //readsome(); 

    var func = (function readsome() {
    var stats = fs.fstatSync(file); // yes sometimes async does not make sense!
    if(stats.size<readbytes+1) {
        console.log('Hehe I am much faster than your writer..! I will sleep for a while, I deserve it!');
        setTimeout(readsome, 1000);
    }
    else {
        fs.read(file, new Buffer(bite_size), 0, bite_size, readbytes, function (err, bytecount, buff) {
        console.log(buff.toString('utf-8', 0, bytecount));
        readbytes+=bytecount;
        process.nextTick(readsome);
        });
    }
    })(); 

});

1 Answer 1

1

First, instead of using

process.nextTick(readsome);

setImmediate(readsome);

process.nextTick is fairly hard to interrupt; see this discussion.

Next, at the top of readSome, check to see if you should be canceled and if so, then return. You could set a global variable when you want to cancel the function, or otherwise, include it in some request state. The specifics of where to store the information about how to cancel depending on what conditions you want to cancel under.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked !!! Thanks a lot. I just did as suggested and changed the global variable value via another api call in same file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.