0

I've managaed to randomly select a line in a .txt file but I'm not sure how I would go about deleting it/removing it.

This is what I'm using to pick a random line, which works fine:

const data = fs2.readFileSync('./randomstuff.txt')
const splitData = data.toString().split("\n");
const randomNumber = Math.floor(Math.random() * splitData.length);
const line = splitData.splice(randomNumber, 1);

How would I then delete "line" from the file? Thanks guys, been struggling with this for a while.

Surve
  • 79
  • 1
  • 1
  • 8
  • You can overwrite the file after splicing the line out. I recommend not using `readFileSync`--it's going to block your process when it could be doing useful work while waiting for disk access. – ggorlen Jul 12 '20 at 20:10
  • Does this answer your question? [Writing files in Node.js](https://stackoverflow.com/questions/2496710/writing-files-in-node-js) – ggorlen Jul 12 '20 at 20:13

2 Answers2

1

You've read the file into a string buffer and removed a "random" line from said buffer using splice, now all you have to do is write the file with the new buffer.

fs2.writeFileSync('./randomstuff.txt', splitData.join("\n"));
bugcatcher9000
  • 201
  • 2
  • 5
0

After deleting the random line from the splitData array, you need to overwrite the contents of the file

fs2.writeFileSync('./randomstuff.txt', splitData.join('\n'));
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26