Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

how to add a first line to a text file in node.js (using fs)

how to add a first line to a text file in node.js (using fs)

Problem

I'm trying to add a first line to an existing text file using node.js.

My actual code looks as follows: var fs = require('fs');

fs.appendFile('test.txt', 'X        Y', function (err) {

});   

The text: 'X Y' is not added as first line, but last.

It would help a lot, if you have an idea, how to add my line as first of the document! :-)

Greetings, JS

Problem Courtesy of: JSt

Solution

You can't. The file systems are not designed that way. You have to write your line first to a temp file and then append the content of you file. Then rename/move your temp file to the name of the original one. (And be sure there was no error when writing, otherwise you loose the content of the original file.)

Solution courtesy of: CFrei

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

how to add a first line to a text file in node.js (using fs)

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×