Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs prepending to a file

For Node.js, what is the best way to prepend to a file in a way SIMILAR to

fs.appendFile(path.join(__dirname, 'app.log'), 'appendme', 'utf8')

Personally, the best way really revolves around a asynchronous solution to create a log where I can basically push onto the file from the top.

like image 238
Mathew Kurian Avatar asked Mar 15 '13 02:03

Mathew Kurian


3 Answers

This solution isn't mine and I don't know where it's from but it works.

const data = fs.readFileSync('message.txt')
const fd = fs.openSync('message.txt', 'w+')
const insert = Buffer.from("text to prepend \n")
fs.writeSync(fd, insert, 0, insert.length, 0)
fs.writeSync(fd, data, 0, data.length, insert.length)
fs.close(fd, (err) => {
  if (err) throw err;
});
like image 79
galki Avatar answered Oct 18 '22 18:10

galki


It is impossible to add to a beginning of a file. See this question for the similar problem in C or this question for the similar problem in C#.

I suggest you do your logging in the conventional way (that is, log to the end of file).

Otherwise, there is no way around reading the file, adding the text to the start and writing it back to the file which can get really costly really fast.

like image 40
Benjamin Gruenbaum Avatar answered Oct 18 '22 17:10

Benjamin Gruenbaum


It seems it is indeed possible with https://www.npmjs.com/package/prepend-file

like image 43
ChrisRich Avatar answered Oct 18 '22 17:10

ChrisRich