I've been trying to get my head around this piece of code. I understand what it does functionally but I have trouble understanding the technical parts.
The code below gets a file as input, reads it and displays the lines as buffers on screen
var fs = require('fs')
var file = fs.readFileSync(process.argv[2])
var offset = 0
for (var i = 0; i < file.length; i++) {
if (file[i] === 10) {
console.log(file.slice(offset, i))
i++
offset = i
}
}
console.log(file.slice(offset, i))
From what I've seen is that the "file[i] === 10" splits the buffer at every new line, but I fail to understand what the number 10 means in this case. Any suggestions?
From the fs.readFileSync(filename, [options])
docs:
If the
encoding
option is specified then this function returns a string. Otherwise it returns a buffer.
There is no encoding
option indicated here, so it returns a buffer.
From the Buffer
docs:
buf[index]
Get and set the
octet
at index. The values refer to individual bytes, so the legal range is between0x00
and0xFF
hex or0
and255
.
So, file[i]
reads the i
th byte of the file. file[i] == 10
checks if the i
th byte of the file is the value 10
.
In ASCII, the value 10 corresponds to LF
line feed character used in newlines; this logic is probably meant to check for newlines in the file and output when an entire line has been read.
The === operator in javascript means: equal value and equal type
So the value of f[i] must be 10 and exactly the number 10 that means the character LF in ascii.