Abhishek Srivastava
Abhishek Srivastava

Reputation: 561

Deleteing characters from end of a file in Nodejs

I am using fs module's appendFile() function to append JSON data to a file.

After appending I need to delete the last character from the file and append a new character. I tried to use \b escape sequence to delete the last character but it did'nt work.

Besides it would be very helpful to know how to edit characters in the middle of the file.

Upvotes: 0

Views: 1652

Answers (1)

Oyeyemi Clement
Oyeyemi Clement

Reputation: 11

You can try this; Replace the closing the brace ']' of the JSON inside the file with 'comma' using

var fd = fs.openSync("file.txt", "r+");
var currentDataLength = data.length;
var buf = new Buffer(","); // create a buffer
  if(currentDataLength > 2) {
    fs.writeSync(fd, buf, 0, buf.length, currentDataLength-1); // this replaces '[' with ',' to separate the objects in the JSON
}

var inputData = `${JSON.stringify({testData: 'Dare Something'})}]`; //  notice that array closing brace ']' is included
currentDataLength += inputData.length; //update the variable holding the JSON Data length of you file

fs.writeFileSync('file.txt', inputData, {encoding: 'utf8', flag: 'a+'}); //updates file

Upvotes: 1

Related Questions