So just to give you some context, I'm trying to create a generator that will create some files (based on user input of course) as well as update some existing files in the project (like adding a new route for example).
Creating the files using this.template
is no problem... the question is: is there any way to do this with Yeoman without having to read the file using Node and doing some fanciful find and replace?
Ok, so I found the answer to my question.
Addy Osmani showed me where to look in this thread on twitter, and then I later found this link which shows exactly what I need.
The gist of it boils down to two functions :
readFileAsString
andwrite
. Usage is as follows:Edit: I've also blogged about this on my blog.
EDIT 1
As mentionned in comments by Toilal :
EDIT 2
And then, as mentionned in comments by ivoba:
Yeoman also provides a more elegant way of fs operations using mem-fs-editor.
You can use
this.fs.copy
, passing a process function as an option to do any modifications to the content:This way you can also take advantage of
mem-fs-editor
features.In combination with @sepans' excellent answer, instead of using regular expressions, one can use some parser.
From Yeoman documentation:
More specifically, when using esprima you will most probably require also some generator such as escodegen to generate js back.
Note that you can use the same path in
from
,to
arguments in order to replace the existing file.On the other hand, the downside of such parsers is that in some cases it may alter the original file way too much, and although safe, this is more intrusive.