Javascript – nodejs prepending to a file

javascriptnode.js

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.

Best Answer

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;
});