I'm writing a command line tool to help me scaffold my projects. I need to be able to add a line of text to a file but to a specific location. Here is the example:
I have this routes.js
file:
router.map({
'/home':{
name: 'home',
component: Home
},
'/about':{
name: 'about',
component: About
},
'/quote':{
name: 'quote',
component: Quote
}
})
Now I want to run a command to create a new route so my-cli generate route ExampleRoute
And I would like it to write the route like so:
router.map({
'/home':{
name: 'home',
component: Home
},
'/about':{
name: 'about',
component: About
},
'/quote':{
name: 'quote',
component: Quote
},
'/example-route':{
name: 'example-route',
component: ExampleRoute
}
})
Appending to the bottom of a file is easy but how do I write to a specific location?
For small files like this it is best to read the file into memory, modify it, and write it back out again.
One possibility is to read it in to a list of strings, one per line. Then insert the added lines into the list. Then write out the list back to the file.
Another possibility would be to parse the file into a map, insert the new elements into the map, and then write the contents of the map out to the file in the required format.
Alternatively if you always want to insert the new text at a fixed offset from the end of the file, you could read into a string, and insert your new text at the end, like so:
package main
import (
"io/ioutil"
"log"
)
const textToInsert = `,
'/example-route':{
name: 'example-route',
component: ExampleRoute
}
})
`
func main() {
original, err := ioutil.ReadFile("routes.js")
if err != nil {
log.Fatal(err)
}
// replace last 4 characters with textToInsert
modified := append(original[0:len(original)-4], []byte(textToInsert)...)
err = ioutil.WriteFile("routes.js", modified, 0644)
if err != nil {
log.Fatal(err)
}
}