我一直在努力理解这段代码。我了解它的功能,但我无法理解其技术部分。
下面的代码获取一个文件作为输入,读取它并将这些行显示为屏幕上的缓冲区
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))
据我所知,“file[i] === 10”在每个新行处分割缓冲区,但我无法理解数字 10 在这种情况下意味着什么。有什么建议吗?
最佳答案
来自fs.readFileSync(filename, [options])
docs :
If the
encoding
option is specified then this function returns a string. Otherwise it returns a buffer.
此处没有指示编码
选项,因此它返回一个缓冲区。
来自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
.
因此,file[i]
读取文件的第 i
th 字节。 file[i] == 10
检查文件的第 i
th 字节是否为值 10
。
在 ASCII ,值 10 对应于换行符中使用的 LF
换行符;这个逻辑可能是为了检查文件中的换行符,并在读取整行时输出。
关于javascript - file[i] === 10 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25536135/