Skip to content

Instantly share code, notes, and snippets.

@dvvtms
Last active April 11, 2019 10:49
Show Gist options
  • Save dvvtms/b14681ef70717002c243c2212753d3ec to your computer and use it in GitHub Desktop.
Save dvvtms/b14681ef70717002c243c2212753d3ec to your computer and use it in GitHub Desktop.
/**
 * Add string to a specified line to a string
 *
 * https://stackoverflow.com/questions/30764424/insert-string-at-line-number-nodejs
 *
 * @param {*} prevText String
 * @param {*} lineNumber Number
 * @param {*} data String
 */
const addStringToLine = (prevText, lineNumber, data) => {
  let splitted = prevText.split("\n");
  splitted.splice(lineNumber, 0, data);
  let nextText = splitted.join("\n");
  
  return nextText;
};

// var fs = require("fs");
// var prevText = fs.readFileSync("gist.md").toString();
// var result = addStringToLine(prevText, 2, "my text");

// fs.writeFile("file.txt", result, function(err) {
//   if (err) return console.log(err);
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment