javascript - file[i] === 10 是什么意思?

标签 javascript node.js

我一直在努力理解这段代码。我了解它的功能,但我无法理解其技术部分。

下面的代码获取一个文件作为输入,读取它并将这些行显示为屏幕上的缓冲区

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 between 0x00 and 0xFF hex or 0 and 255.

因此,file[i] 读取文件的第 ith 字节。 file[i] == 10 检查文件的第 ith 字节是否为值 10

ASCII ,值 10 对应于换行符中使用的 LF 换行符;这个逻辑可能是为了检查文件中的换行符,并在读取整行时输出。

关于javascript - file[i] === 10 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25536135/

相关文章:

node.js - Neo4j事务误区

node.js - Meteor、npm 和请求

node.js - 如何修复 "Response to preflight request doesn' t 通过访问控制检查 : It does not have HTTP ok status"error in react app with nodejs api

javascript - 使用node.js将rails应用程序部署到ubuntu

javascript - HTML/JavaScript : Overwrite file every time it downloads

javascript - 在riotjs中加载外部库

javascript - Javascript 中的 PHP 数组?

node.js - 使用 Inspector 协议(protocol)的 VSCode 调试 Node 应用程序

javascript - 来自响应的数据是无法设置为 iframe 的符号

javascript - 无法在 VS Code 中调试当前的 typescript 文件,因为找不到相应的 JavaScript