Read the file one character at a time in node.js?

Is there a way to read one character at a time in nodejs from a file without storing the whole file in memory? I found an answer for strings

I tried something like this, but this does not help:

const stream = fs.createReadStream("walmart.dump", {
    encoding: 'utf8',
    fd: null,
    bufferSize: 1,
});
stream.on('data', function(sym){
    console.log(sym);
});
+5
source share
2 answers

The read stream has a read () method , where you can pass the size of the read characters. Code example:

var readable = fs.createReadStream("walmart.dump", {
    encoding: 'utf8',
    fd: null,
});
readable.on('readable', function() {
  var chunk;
  while (null !== (chunk = readable.read(1))) {
    console.log(chunk); // chunk is one symbol
  }
});
+7
source

Below is an example of a lower level: fs.read (fd, buffer, offset, length, position, callback)

using:

const fs = require('fs');

// open file for reading, returns file descriptor
const fd = fs.openSync('your-file.txt','r');

function readOneCharFromFile(position, cb){

        // only need to store one byte (one character)
        const b = new Buffer(1);

        fs.read(fd, b, 0, 1, position, function(err,bytesRead, buffer){
            console.log('data => ', String(buffer));
            cb(err,buffer);
        });

}

you will need to increase the position when you read the file, but it will work.

here's a quick example of how to read the entire file, character by character

script, ,

const async = require('async');
const fs = require('fs');
const path = require('path');


function read(fd, position, cb) {

    let isByteRead = null;
    let ret = new Buffer(0);

    async.whilst(
        function () {
            return isByteRead !== false;
        },
        function (cb) {
            readOneCharFromFile(fd, position++, function (err, bytesRead, buffer) {

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

                isByteRead = !!bytesRead;
                if(isByteRead){
                    ret = Buffer.concat([ret,buffer]);
                }

                cb(null);
            });
        },
        function (err) {
            cb(err, ret);
        }
    );

}


function readOneCharFromFile(fd, position, cb) {

    // only need to store one byte (one character)
    const b = new Buffer(1);
    fs.read(fd, b, 0, 1, position, cb);

}


 /// use your own file here
const file = path.resolve(__dirname + '/fixtures/abc.txt');
const fd = fs.openSync(file, 'r');

// start reading at position 0, position will be incremented
read(fd, 0, function (err, data) {
    if (err) {
        console.error(err.stack || err);
    }
    else {
        console.log('data => ', String(data));
    }
    fs.closeSync(fd);
});

, , . , OS , . async.whilst() , , (ret isByteRead). , , .

+1

All Articles