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)
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.
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 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With