Insert string at line number nodejs
Asked Answered
S

3

20

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

Scots answered 10/6, 2015 at 18:26 Comment(1)
How large is the text file? Can you read it in into a String, then split by newlines, insert an element into the array, and then output the array to another file? Or do you have memory concerns?Bream
B
40

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);
});
Bream answered 10/6, 2015 at 18:46 Comment(0)
S
0

A simpler version of @VineetKosaraju code would be:

let yaml_str = `---
up:
tags:
related: candidate
uuid: "20240215"
---
`

const lineNumber = 1                             // at the top
var txt = yaml_str.toString().split("\n");
txt.splice(lineNumber, 0, "location: 'Houston'");
txt = txt.join("\n");

console.log(txt)

I am using this in Obsidian.md to edit YAML frontmatter.

The output is:

---
location: 'Houston'
up:
tags:
related: candidate
uuid: "20240215"
---
Spoonful answered 16/2 at 15:53 Comment(0)
K
-2

If you are on a Unix system then you probably want to use sed, like so to add some text to the middle of the file:

#!/bin/sh
text="Text to add"
file=data.txt

lines=`wc -l $file | awk '{print $1}'`

middle=`expr $lines / 2`

# If the file has an odd number of lines this script adds the text
# after the middle line. Comment this block out to add before
if [ `expr $lines % 2` -eq 1 ]
then
  middle=`expr $middle + 1`
fi

sed -e "${middle}a $text" $file

Note: above example is from here.

With NodeJS it appears that there are some npm packages that might help, like sed.js, or replace.

Karinkarina answered 10/6, 2015 at 18:57 Comment(1)
The question is specifically how to achieve this using NodeJS.Tropine

© 2022 - 2024 — McMap. All rights reserved.