'Adding content in file in specific place with node js (Like Angular Cli Modify app.module file)
I got the idea that node js its not just for web application for example I can create a console application with node (cli) . and already I have an interest in how I can make a cli app that create files and modify existing files for example something like angular cli with one command "ng generate component" its :-
1- create a set of files
2- modify app.module file
a. add import statement for generated component
b. add generated component in declarations array
and after a lot of search I got that first step can be handled in some way with node file system module.
but i don't know how they modify "app.module" file by just adding some syntax in its right place for instance adding new import statement after all exists import statements also adding the component name in declarations array as a last item I'm really appreciate any help maybe with some code example if possible and thanks in advance
Solution 1:[1]
After some searches i found this answer:
There a couple of ways of editing a file, the most reliable is perhaps the most complex one which can be done by parsing the file (Generating an abstract syntax tree) update the new ast and pass it to a code generator which will output the new string (code) of the modified ast. Another option is to use regular expressions to know where add to certain statements. For example there would be a regex to match import statements to lines, you will map the lines of the file to this regex where you'll get an array of booleans denoting whether the line is an import stmt. Or not, once the import stmts are finished you can insert a new line with the new import statement in the original lines array. A third option is to regenerate the file all at once everytime, but this means that you'll have to a ctx of the project (ctx = object contains some details.
and as reference i found that AST (Abstract Syntax Tree) is more reliable way also it's not that hard this is some links that helped me a lot to know what is AST in simple way and how to deal with it
1- What is AST and how to understand it and how to use it https://www.youtube.com/watch?v=tM_S-pa4xDk
2- and this is an amazing article about "Write Code to Rewrite Your Code with jscodeshift" https://www.toptal.com/javascript/write-code-to-rewrite-your-code https://www.youtube.com/watch?v=tM_S-pa4xDk
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |