Somnath
Somnath

Reputation: 3277

How to stop/abort reading file in node.js

Lets think I'm reading a file 500 MB asynchronously. Which takes time to read. Now while reading the file asynchronously how can I stop/abort reading the file and call a callback (i.e. successfullyAbort) function?

fs.readFile(filePath, function(err, data) {
    //Do work
});

Upvotes: 3

Views: 3004

Answers (2)

freakish
freakish

Reputation: 56467

Just use fs.read (with fs.open) instead of fs.readFile. Example:

fs.open(filepath, 'r', function(err, fd) {

    var finalize = function(buffer) {
        fs.close(fd);
        console.log(buffer);
    };

    if (err) {
        finalize();
        return;
    }

    fs.fstat(fd, function(err, stats) {
        if (err) {
            finalize();
            return;
        }

        var bufferSize = stats.size,
            chunkSize = 512,
            buffer = new Buffer(bufferSize),
            bytesRead = 0;

        var inner_read = function() {
            if ((bytesRead + chunkSize) > bufferSize) {
                chunkSize = (bufferSize - bytesRead);
            };
            if (chunkSize > 0) {
                fs.read(fd, buffer, bytesRead, chunkSize, bytesRead, function(err) {
                    // YOU CAN DO SOMETHING HERE TO STOP READING
                    if (err) {
                        finalize(buffer);
                        return;
                    }
                    bytesRead += chunkSize;
                    inner_read();
                });
            } else {
                finalize(buffer);
            }
        }
        inner_read();
    });
});

Upvotes: 1

NilsH
NilsH

Reputation: 13821

fs.readFile does indeed read a file asynchronously, but it will not invoke your callback until the entire file has been read, so you cannot achieve this by using that method. Instead, I believe you have to use fs.createReadStream() which gives you a stream.Readable. Then you can implement the appropriate events for this object.

function readTheFile(fileName, callback) {
    var stream = fs.createReadStream(fileName);
    stream.on('readable', function() {}); // Do your read logic
    stream.on('error', function(err) {}); // Handle the error
}

Upvotes: 1

Related Questions