Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 317
Payne Chu Avatar asked Jul 11 '13 06:07

Payne Chu


People also ask

How do I replace a string with a string in Node JS?

Make sure to open your terminal in the same directory and run the file with node index.js. Alternatively, you can use promises. Use the fsPromises.readFile () method to read the file. Use the replace () method to replace the string with the replacement.

How do I read a node file in Node JS?

Node.js comes with the fs module. This module contains a readFile method. This readFile method accepts two arguments: the file path and options how to return the contents. You can return the file content as a string using the string value 'utf8' as the encoding option.

How do I create an empty file in Node JS?

How to Create an Empty File Node.js comes with the fs module. This module contains a readFile method. This readFile method accepts two arguments: the file path and options how to return the contents. You can return the file content as a string using the string value 'utf8' as the encoding option.

How to replace a string in a file using Python?

We used the String.replace method to replace a string in the file. The first parameter we passed to the replace method is a regular expression and the second - the replacement string. The forward slashes / / mark the beginning and end of the regular expression. The g flag stands for global and replaces all occurrences of the matched string.


1 Answers

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.

like image 93
c.P.u1 Avatar answered Sep 24 '22 13:09

c.P.u1