1

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

2 Answers 2

3

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

i was looking for same, but your answer hurt me
Any better idea welcome. Can we talk about removing lines from the beginning of a file, too? ;-)
1

I was working on this, and here is my solution

const file = 'test.txt'
fs.readFile(file, 'utf8', (err, data) => {
    if (err) throw err
    const newData = data.replace(/^/, `text to the first line`)
    fs.writeFile(file, newData, function (err) {
      if (err) throw err;
      console.log('Saved!')
    })
  }
)

So first, you have to read the file. After that, you can add your string to the first line with replace method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.