You are currently viewing Node.js Script to Automatically Create a File and Folder Structure

Node.js Script to Automatically Create a File and Folder Structure

🛠️ How to Use a Node.js Script to Automatically Create a File and Folder Structure

If you’re setting up new projects often, you know how repetitive it can be to create the same file and folder structure every time. Whether you’re starting a new web app, API, or microservice, a Node.js script can save you time and effort by generating your file structure in seconds.

In this post, we’ll walk through how to write a Node.js script that creates a custom folder and file layout — perfect for automating your project setups.


🚀 Why Automate File/Folder Creation?

Manually creating folders and files can be tedious. With automation:

  • You save time
  • Reduce human error
  • Ensure consistency across all your projects

Let’s jump into the code.


📁 Example Folder Structure

Here’s the structure we’ll generate:

pgsqlCopyEditmy-app/
├── src/
│   ├── index.js
│   └── utils/
│       └── helper.js
├── public/
│   └── index.html
└── README.md

📜 Node.js Script

Here’s a basic Node.js script to create this structure:

javascriptCopyEditconst fs = require('fs');
const path = require('path');

// Define the folder and file structure
const structure = {
  'my-app': {
    'src': {
      'index.js': '',
      'utils': {
        'helper.js': ''
      }
    },
    'public': {
      'index.html': '<!DOCTYPE html><html><head><title>My App</title></head><body></body></html>'
    },
    'README.md': '# My App\n\nGenerated by Node.js script.'
  }
};

// Recursive function to create folders and files
function createStructure(basePath, obj) {
  Object.entries(obj).forEach(([name, content]) => {
    const fullPath = path.join(basePath, name);

    if (typeof content === 'string') {
      fs.writeFileSync(fullPath, content);
      console.log(`Created file: ${fullPath}`);
    } else {
      if (!fs.existsSync(fullPath)) {
        fs.mkdirSync(fullPath);
        console.log(`Created folder: ${fullPath}`);
      }
      createStructure(fullPath, content);
    }
  });
}

// Run the script
createStructure(__dirname, structure);

🧪 How to Use It

  1. Save the script as generateStructure.js
  2. Open your terminal
  3. Run the script with:
node generateStructure.js

That’s it! You’ll see the my-app directory created in the current location with the entire structure inside.


🧩 Customize It

Want to customize for your own projects? Just modify the structure object to match your preferred layout. You can add more folders, files, and even templates.


✅ Final Thoughts

Automating folder and file setup is a simple but powerful productivity hack. With Node.js, it only takes a few lines of code to make your dev workflow faster and cleaner.

💬 Got a cool folder structure you always use? Share it in the comments — we’d love to see it!

****************************************************

Real case example

Here’s a breakdown of the generateStructure.js script that builds the small-group-messenger project structure:


🔍 High-Level Overview

The script:

  1. Defines the desired folder and file layout in an object.
  2. Walks through this layout recursively.
  3. Creates each folder and file in the right place using Node.js fs (filesystem) module.

🧱 Code Explained, Section by Section

1. Imports Required Modules

jsCopyEditconst fs = require('fs');
const path = require('path');
  • fs: Node’s built-in module for interacting with the file system.
  • path: Helps build file paths in a cross-platform way (works on Windows/Linux/Mac).

2. Defines the Project Structure

jsCopyEditconst structure = {
  'small-group-messenger': {
    files: [
      '.env',
      '.gitignore',
      'package.json',
      'package-lock.json',
      'Procfile',
      'server.js'
    ],
    folders: {
      models: ['User.js', 'Group.js', 'Message.js'],
      routes: ['auth.js', 'groups.js', 'messages.js'],
      middleware: ['auth.js', 'errorHandler.js'],
      config: ['db.js'],
      public: {
        files: ['index.html', 'styles.css', 'favicon.ico'],
        folders: {
          images: ['default-avatar.png'],
          js: ['app.js', 'socket.js', 'ui.js']
        }
      },
      tests: ['api.test.js', 'socket.test.js']
    }
  }
};
  • It describes all top-level files and folders.
  • Nested structure (publicfoldersjs) is handled recursively.
  • Files are in arrays, folders are either arrays (if simple) or nested objects (if complex).

3. Recursive Structure Creator Function

jsCopyEditfunction createStructure(basePath, structure) {
  for (const folderName in structure) {
    const folderPath = path.join(basePath, folderName);
    fs.mkdirSync(folderPath, { recursive: true });
  • Loops over each key (like small-group-messenger, models, etc.)
  • Creates each folder using fs.mkdirSync with recursive: true (in case parents don’t exist).
jsCopyEdit    const { files = [], folders = {} } = structure[folderName];
  • Extracts files and folders in each directory, with defaults in case they’re missing.
jsCopyEdit    files.forEach(file => {
      fs.writeFileSync(path.join(folderPath, file), '');
    });
  • Creates each file with empty content using fs.writeFileSync.
jsCopyEdit    for (const subFolder in folders) {
      const content = folders[subFolder];
      if (Array.isArray(content)) {
        ...
      } else {
        createStructure(folderPath, { [subFolder]: content });
      }
    }
  }
}
  • If content is a list (just files), it creates the folder and those files.
  • If content is an object (with deeper folders), it calls itself recursively.

4. Execute the Function

jsCopyEditcreateStructure(process.cwd(), structure);
console.log('✅ small-group-messenger structure created.');
  • Runs the function starting from the current directory.
  • Logs success when done.

✅ Summary

  • Cleanly organizes and automates project setup.
  • Recursive logic allows for deeply nested structures.
  • Easy to extend—just add folders/files to the structure object.

Leave a Reply