2

I want to read the size of bytes of a file as I read it. I have this

var path = 'training_data/dat1.txt';

var fs = require("fs"); //Load the filesystem module
var stats = fs.statSync(path);
var fileSizeInBytes = stats["size"];

var accSize = 0;

var lineReader = require('readline').createInterface({
    input: fs.createReadStream(path)
});
lineReader.on('line', function (line) {
    accSize += Buffer.byteLength(line, 'utf8');
    console.log(accSize + "/" + fileSizeInBytes);
});
lineReader.on('close', function() {
    console.log('completed!');
});

But it doesn't print out the correct filesize.

7/166
16/166
23/166
32/166
39/166
48/166
55/166
64/166
71/166
80/166
87/166
96/166
103/166
112/166

it prints this for example.

Does anyone know whats wrong?

0

1 Answer 1

2

The lineReader doesn't include the newline \n character in the buffer as each line is read, which is where your bytes are missing.

Try this:

accSize += Buffer.byteLength(line + '\n', 'utf8');

EDIT

If the file being read uses Windows line endings, you'll need to add two characters, since those will also have a carriage return in addition to line feed, denoted as '\r\n'. (see this for more details)

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

2 Comments

It worked when I did + '\\n' (its actually 3 more characters for some reason), and then since the last line doesn't have a new line character, I just added 2 to the total size, and then in the end, it printed 168/168.
'\n' is actually a single character. By adding an additional '\', you are escaping the other '\', so instead of newline, you're using the literal string '\n'. In any case, if you needed to add two characters, it's probably because your document is formatted with windows line endings, which include a carriage return ('\r\n'). I'll add that to my answer

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.