DEV Community

hmintoh
hmintoh

Posted on • Updated on

How to: Automate file creation with node's fs module

TL;DR

Do you ever find yourself creating the same files over and over again and wish for a script to do the boring work for you without having to use a third-party library?

The story

I've been creating a lot of React components lately and wanted to find a way to automate file creation. Specifically, a script that could create a ComponentName folder containing the following files:

  • index.tsx
  • styles.tsx

After doing some research, I found that node's fs module is able to meet my needs. Specifically,

  • fs.mkdirSync(path) synchronously creates a directory given a path (+ other options)
  • fs.writeFileSync(filepath, content) synchronously creates files in the given filepath and optionally fills them with content

Step 1: Defining the file templates

// src/scaffold.js
const templates = {
  index: `// Comment to begin our index file`,
  styles: `// Comment to begin our styles file`,
};
Enter fullscreen mode Exit fullscreen mode

Step 2: Write functions to create the component folder and files

// src/scaffold.js
const fs = require("fs");
const args = process.argv.slice(2);

function createFolder(component) {
  const directory = `./src/components/${component}`;

  if (!fs.existsSync(directory)) {
    fs.mkdirSync(directory);
  }
}

function writeFile(component, type) {
  const filepath =`./src/components/${component}/${filename}.tsx`;

  fs.writeFile(filepath, templates[type], (err) => {
    if (err) throw err;
    console.log("Created file: ", filepath);
    return true;
  });
}

function generate(component) {
  createFolder(component);

  const fileTypes = ["index", "styles"];

  for (let type of fileTypes) {
    writeFile(component, type)
  }
}

generate(args[0]);
Enter fullscreen mode Exit fullscreen mode
  • createFolder(component) creates a folder named component if it does not exist in the specified path
  • writeFile(component, type) creates files in the specified folder and fills them with content specified in templates[type]

Step 3: Adding the script

Finally, add the following script to package.json

 "scripts": {
   "component": "node scaffold.js"
 },
Enter fullscreen mode Exit fullscreen mode

That's it! The magic command that is yarn component <ComponentName>.

freedom

Let me know your thoughts in the comments below 👇

Top comments (0)