1

Is there way to append to the beginning of a file in node (maybe to insert). I was looking around her http://nodejs.org/api/fs.html but didn't see anything, I know that append brings adds to the end of the file, but is there a way to add to the beginning of a file?

Thanks

ChewOnThis_Trident
  • 2,105
  • 2
  • 18
  • 22

2 Answers2

2

No, there is no built in way to insert at the beginning of the file in nodejs.

This is nothing specific to nodejs, it's the same way in C C# Java Python and pretty much any other languages I know and is just how the file system works. ( here is why not by the way)

You can however, read the file with fs.readFile and then write it back with the stuff you need added.

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
1

You can do it the "unix" way with shelljs and pipes.

const shell = require('shelljs')
shell
  .echo('This line will be on top\n')
  .cat('originalFile.txt')
  .to('originalFile.txt')
alfonsodev
  • 2,714
  • 2
  • 23
  • 30