微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如果偏移量在文件范围内,为什么Node.js会抱怨ERR_OUT_OF_RANGE?

如何解决如果偏移量在文件范围内,为什么Node.js会抱怨ERR_OUT_OF_RANGE?

我正在尝试通过4字节缓冲区以迭代偏移量覆盖预生成的1GB文件的某些内容

据我所知,我使用的是正确的标志:

const fd = fs.openSync(dataPath,"r+") // also tried "a+"

enter image description here

文件大小在范围内

let stats = fs.statSync(dataPath)
let fileSizeInBytes = stats["size"]
let fileSizeInMegabytes = fileSizeInBytes / 1000000
console.log("fileSizeInMegabytes",fileSizeInMegabytes) // => fileSizeInMegabytes 1000

但是当我尝试编写更新时:

const bufferSize = 74

let pointer = (timestampSet.size * 4) + 4
for (let j = 0; j < timestampSet.size; j++) {
  pointer += mapIterator.next().value * bufferSize
  const pointerBuffer = Buffer.alloc(4)
  pointerBuffer.writeUInt32BE(pointer,0) // <Buffer 00 2e 87 e4>
  console.log("writing",pointerBuffer,"to file",dataPath,"at offset",j * 4)
  // writing <Buffer 00 2e 87 e4> to file E://data.odat at offset 4
  fs.writeSync(fd,j * 4,4)
}
fs.close(fd).then(() => {
  console.log("write stream closed")
})

iterateProcess()

我得到了错误

RangeError [ERR_OUT_OF_RANGE]: The value of "length" is out of range. It must be <= 0. Received 4

如果文件大小正确且使用了正确的标志,为什么会发生此错误

解决方法

您似乎误解了writeSync参数。 offset是指缓冲区中的位置,而不是文件中的位置。对于文件中的地址,请使用position

错误消息来自以下事实:系统无法从您指定的缓冲区位置开始在缓冲区中找到4个字节。

您的代码应为:

fs.writeSync(fd,pointerBuffer,4,j*4)

来自docs

offset确定要写入的缓冲区部分,length是一个整数,指定要写入的字节数。

position指的是距应写入此数据的文件开头的偏移量。如果为typeof position !== 'number',则数据将被写入当前位置。 [..]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。