Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert string at line number nodejs

I have a file that I would like to modify. Is there a way to insert a string to a file at a specific line number? with NodeJS

I really thank you for helping me out

like image 535
Wouter Avatar asked Jun 10 '15 18:06

Wouter


1 Answers

As long as the text file isn't that large, you should be able to just read in the text file into an array, insert an element into the specific line index, and then output the array back to the file. I've put some sample code below - make sure you change 'file.txt', "Your String" and the specific lineNumber.

Disclaimer, I haven't had time to test the below code yet:

var fs = require('fs');

var data = fs.readFileSync('file.txt').toString().split("\n");
data.splice(lineNumber, 0, "Your String");
var text = data.join("\n");

fs.writeFile('file.txt', text, function (err) {
  if (err) return console.log(err);
});
like image 147
Vineet Kosaraju Avatar answered Nov 08 '22 17:11

Vineet Kosaraju