DEV Community

hmintoh
hmintoh

Posted on β€’ Edited on

1

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 πŸ‘‡

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay