Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write text in the middle of a file with fs.createWriteStream ? (or in nodejs in general)

I'm trying to write in a text file, but not at the end like appendFile() do or by replacing the entiere content...

I saw it was possible to chose where you want to start with start parameter of fs.createwritestream() -> https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options

But there is no parameter to say where to stop writting, right ? So it remove all the end of my file after I wrote with this function.

const fs = require('fs');

var logger = fs.createWriteStream('result.csv', {
  flags: 'r+', 
  start: 20 //start to write at the 20th caracter
})

logger.write('5258,525,98951,0,1\n') //example a new line to write

Is there a way to specify where to stop writting in the file to have something like:

  • ....
  • data from begining
  • ....
  • 5258,525,98951,0,1
  • ...
  • data till the end
  • ...
like image 973
Dimitri Avatar asked Nov 19 '25 11:11

Dimitri


1 Answers

I suspect you mean, "Is it possible to insert in the middle of the file." The answer to that is: No, it isn't.

Instead, to insert, you have to:

  1. Determine how big what you're inserting is
  2. Copy the data at your insertion point to that many bytes later in the file
  3. Write your data

Obviously when doing #2 you need to be sure that you're not overwriting data you haven't copied yet (either by reading it all into memory first or by working in blocks, from the end of the file toward the insertion point).


(I've never looked for one, but there may be an npm module out there that does this for you...)

like image 188
T.J. Crowder Avatar answered Nov 22 '25 00:11

T.J. Crowder