如果偏移量在文件范围内,为什么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',则数据将被写入当前位置。 [..]