1

I'm simply trying to overwrite the contents of a pre-generated (written with allocUnsafe(size)) 1GB file via a 4 byte buffer at an iterating offset, and before I open the file descriptor, fs.stat and the Windows file system show the correct size. As soon as I open the file descriptor, it appears both in fs.stat and in the file system the file is empty:

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

fd = fs.openSync(dataPath, 'w')

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

Why is opening the file descriptor emptying my file? Surely I'm missing something obvious, but I can't see it.

J.Todd
  • 707
  • 1
  • 12
  • 34
  • 3
    File opening "w" truncates the file. You should use "r+" , find a list here https://nodejs.org/api/fs.html#fs_file_system_flags. – snwflk Sep 20 '20 at 21:43
  • Good use of editing the question, recognizing there are actually 2 questions at hand, and splitting the rest off into a new question! – snwflk Sep 20 '20 at 23:03

1 Answers1

3

Opening the file using the w flag truncates the file, i.e. removes any contents.

You should use r+ to read and write to the file without wiping it clean.

For more info, check out the Node docs and the answers on this question.

snwflk
  • 3,341
  • 4
  • 25
  • 37
  • Thanks. Still having an issue with the correct flag, but it ends up being a different question: https://stackoverflow.com/questions/63984177/why-is-node-js-complaining-err-out-of-range-if-the-offset-is-within-the-files-r – J.Todd Sep 20 '20 at 22:37