Payne Chu
Payne Chu

Reputation: 573

node.js how to insert string to beginning of file but not replace the original text?

The code below inserted somestring to file but also will replace the text inside the file. how can fix this?

fd = fs.openSync('file', 'r+')
buf = new Buffer('somestring')
fs.writeSync(fd, buf, 0, buf.length, 0)
fs.close(fd)

Upvotes: 21

Views: 23182

Answers (2)

c.P.u1
c.P.u1

Reputation: 17094

Open the file in append mode using the a+ flag

var fd = fs.openSync('file', 'a+');

Or use a positional write. To be able to append to end of file, use fs.appendFile:

fs.appendFile(fd, buf, err => {
  //
});

Write to the beginning of a file:

fs.write(fd, buf, 0, buf.length, 0);

EDIT:

I guess there isn't a single method call for that. But you can copy the contents of the file, write new data, and append the copied data.

var data = fs.readFileSync(file); //read existing contents into data
var fd = fs.openSync(file, 'w+');
var buffer = Buffer.from('New text');

fs.writeSync(fd, buffer, 0, buffer.length, 0); //write new data
fs.writeSync(fd, data, 0, data.length, buffer.length); //append old data
// or fs.appendFile(fd, data);
fs.close(fd);

Please note that you must use the asynchronous versions of these methods if these operations aren't performed just once during initialization, as they'll block the event loop.

Upvotes: 23

D.Dimitrioglo
D.Dimitrioglo

Reputation: 3663

With small files you can do it like this:

let logPath = path.join(appPath, 'deploy.log');
let logRows = fs.readFileSync(logPath).toString().split('\n');

logRows.unshift('Your string here');
fs.writeFileSync(logPath, logRows.join('\n'));

Hope it would be useful for someone!

Upvotes: 7

Related Questions