Finally we have another function expression called writeToPath. It takes the path and returns another function which accepts a file string and the content of that file. It then writes the file or throws an error (worst case scenario).

Next we define what we want to watch. I’m watching the src/components directory, but you can watch any set of paths. You can even pass an array of paths. If you don’t recognize the ** part in src/components/** — it’s called a glob pattern.

After that, we define what events we want to listen for. I’m only listening for adding a directory with .on(“addDir”) but you can listen for other events too.

Next let’s extract the name of the component by replacing anything before the component name:

src/components/Header/components/Title

becomes

Title

Finally we will check that the component name passes this regex:

/^[^\/_]*$/

So as long as it doesn’t have a forward slash or underscore — it’s good to go. This avoids polluting __tests__ folders or nested/directories by mistake.

So at the top, we declare the files object — it’s a list of file name strings which we’re injecting the name parameter into. You might have noticed that it has the same keys as the templates object. That’s important.

The if statement is very specific to my setup. I don’t want to create my files if the new folder is called components. I am only creating components within a components sub-folder.

writeFile is our function writeToPath partially applied. It’s a function that creates a file in the given path when called with a filename and some content.

toFileMissingBool takes a file name and returns true if that file doesn’t exist in the given path. I know the function names are weird, but I promise it kind of makes more sense in a few lines.

checkAllMissing is a function that we are going to pass to reduce. It takes two booleans and returns true if both are true. This is boolean algebra. We are also using the reduce method of Array. Don’t be afraid of reduce. It’s super cool and really useful in this kind of situation.

Let’s talk about the variable noneExist. If it’s true, then none of the files we want to create exist in the new folder. The idea is that you don’t mess with a folder just because it doesn’t have a test file or a sass file. Maybe that folder doesn’t need one.

We map the values in files to a boolean which represents if that file is missing or not. Then we take that array of booleans and reduce them to a single boolean value which represents whether all the files exist or not.

So if they’re all true, then noneExist is also true. But if even one is false, then noneExist will be false.

Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public. We also have
thousands of freeCodeCamp study groups around the world.