S
S
Shakhrom Mukumov2019-03-13 22:27:52
JavaScript
Shakhrom Mukumov, 2019-03-13 22:27:52

How to automatically create empty files inside a created folder?

Hello everyone, I'm starting to get acquainted with Gulp + BEM .
How to make automatic creation of empty files and folders, when creating new folders (blocks), file names are taken from the name of the folder (parent).
blocks

  • header
    • header.sass
    • header.js
    • header.pug
    • img

  • footer
    • footer.sass
    • footer.js
    • footer.pug
    • img

  • reviews
    • reviews.sass
    • reviews.js
    • reviews.pug
    • img


Those. track created folders (blocks) and automatically create typical files and folders inside.
Now I do all this manually, I wanted to make my life a little easier through automation.
PS I would be grateful if someone shares their experience, who does what, maybe my vision is not quite right and you need to do it differently.
Solution below:
const gulp = require('gulp');
const fs = require('fs');
const allBlocks = './src/blocks/'; // Путь до директории с блоками

// Отслеживаем добавление новых директорий
  gulp.watch(allBlocks).on('addDir', function() {
    const dirs = fs.readdirSync(allBlocks); // Получаем список дочерних директорий
   // Перебираем список с проверкой на наличие внутри директорий совпадений с файлами (.pug/.sass/.js), все эти файлы с названием блока(папки)
    for(i = 0; i < dirs.length;i++){
      if(fs.existsSync(allBlocks+'/'+dirs[i]+'/'+dirs[i]+'.pug') === false && fs.existsSync(allBlocks+'/'+dirs[i]+'/'+dirs[i]+'.sass') === false && fs.existsSync(allBlocks+'/'+dirs[i]+'/'+dirs[i]+'.js') === false){
        fs.appendFileSync(allBlocks+'/'+dirs[i]+'/'+dirs[i]+'.pug', ''); // Добавляем пустой файл с названием блока blockName.pug
        fs.appendFileSync(allBlocks+'/'+dirs[i]+'/'+dirs[i]+'.js', ''); // Добавляем пустой файл с названием блока blockName.js
        fs.appendFileSync(allBlocks+'/'+dirs[i]+'/'+dirs[i]+'.sass', ''); // Добавляем пустой файл с названием блока blockName.sass
      }
      try {
        fs.statSync(allBlocks+'/'+dirs[i]+'/img');
      }
      catch (err) {
        // Если в блоке нет директории img, то соответственно добавляем.
        if (err.code === 'ENOENT') {
          fs.mkdirSync(allBlocks+'/'+dirs[i]+'/img');
          console.log('Папка img добавлена в директорию' + ' — ' + dirs[i]);
        }
      }
    }
  });

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Shakhrom Mukumov, 2019-03-15
@leon9208

const gulp = require('gulp');
const fs = require('fs');
const allBlocks = './src/blocks/'; // Путь до директории с блоками

// Отслеживаем добавление новых директорий
  gulp.watch(allBlocks).on('addDir', function() {
    const dirs = fs.readdirSync(allBlocks); // Получаем список дочерних директорий
   // Перебираем список с проверкой на наличие внутри директорий совпадений с файлами (.pug/.sass/.js), все эти файлы с названием блока(папки)
    for(i = 0; i < dirs.length;i++){
      if(fs.existsSync(allBlocks+'/'+dirs[i]+'/'+dirs[i]+'.pug') === false && fs.existsSync(allBlocks+'/'+dirs[i]+'/'+dirs[i]+'.sass') === false && fs.existsSync(allBlocks+'/'+dirs[i]+'/'+dirs[i]+'.js') === false){
        fs.appendFileSync(allBlocks+'/'+dirs[i]+'/'+dirs[i]+'.pug', ''); // Добавляем пустой файл с названием блока blockName.pug
        fs.appendFileSync(allBlocks+'/'+dirs[i]+'/'+dirs[i]+'.js', ''); // Добавляем пустой файл с названием блока blockName.js
        fs.appendFileSync(allBlocks+'/'+dirs[i]+'/'+dirs[i]+'.sass', ''); // Добавляем пустой файл с названием блока blockName.sass
      }
      try {
        fs.statSync(allBlocks+'/'+dirs[i]+'/img');
      }
      catch (err) {
        // Если в блоке нет директории img, то соответственно добавляем.
        if (err.code === 'ENOENT') {
          fs.mkdirSync(allBlocks+'/'+dirs[i]+'/img');
          console.log('Папка img добавлена в директорию' + ' — ' + dirs[i]);
        }
      }
    }
  });

PS Special thanks to Sergey delphinpro for the tip, for the links to the documentation (to the right section) and to related articles!

A
Adamos, 2019-03-14
@Adamos

#!/bin/bash
mkdir -p $1/img
exts=('sass' 'js' 'pug')
for ext in ${exts[@]}
do
touch $1/$(basename $1).$ext
done

S
Sergey delphinpro, 2019-03-14
@delphinpro

That's right, write a separate task for the gallp or a script to run via npm run
The script is simple: create a folder, create files.
Complete documentation on working with the file system https://nodejs.org/api/fs.html
And a small abstract on the hub https://habr.com/ru/company/ruvds/blog/424969/ (this should be enough)

Z
zverygi, 2019-03-14
@zverygi

a separate script to run via npm, the code below creates a folder and three files .pug, .sass, .js. We put the whole thing in the root of the .js file, well, we edit the path to the shared folder where the modules will be in this line "const BLOCKS_DIR = path.join(__dirname, 'dev/pug/modules');"

// создание блока набрать node block you_block_name
'use strict';

const fs = require('fs')
const path = require('path')
const colors = require('colors')
const readline = require('readline')

const rl = readline.createInterface(process.stdin, process.stdout);

// folder with all blocks
const BLOCKS_DIR = path.join(__dirname, 'dev/pug/modules');

//////////////////////////////////////////////////////////////////////////////////////////////////

// default content for files in new block
const fileSources = {
  pug : `mixin {blockName}()\n\t.{blockName}\n\t\t| {blockName}\n`,
  sass: `/*! {blockName} style */ \n` //можно задать изначальные значения/текст
//	js	: `// .{blockName} scripts goes here`
};

function validateBlockName(blockName) {
  return new Promise((resolve, reject) => {
    const isValid = /^(\d|\w|-)+$/.test(blockName);

    if (isValid) {
      resolve(isValid);
    } else {
      const errMsg = (
        `ERR>>> An incorrect block name '${blockName}'\n` +
        `ERR>>> A block name must include letters, numbers & the minus symbol.`
      );
      reject(errMsg);
    }
  });
}

function directoryExist(blockPath, blockName) {
  return new Promise((resolve, reject) => {
    fs.stat(blockPath, notExist => {
      if (notExist) {
        resolve();
      } else {
        reject(`ERR>>> The block '${blockName}' already exists.`.red);
      }
    });
  });
}

function createDir(dirPath) {
  return new Promise((resolve, reject) => {
    fs.mkdir(dirPath, err => {
      if (err) {
        reject(`ERR>>> Failed to create a folder '${dirPath}'`.red);
      } else {
        resolve();
      }
    });
  });
}

function createFiles(blocksPath, blockName) {
  const promises = [];
  Object.keys(fileSources).forEach(ext => {
    const fileSource = fileSources[ext].replace(/\{blockName}/g, blockName);
    const filename = `${blockName}.${ext}`;
    const filePath = path.join(blocksPath, filename);

    promises.push(
        new Promise((resolve, reject) => {
          fs.writeFile(filePath, fileSource, 'utf8', err => {
            if (err) {
              reject(`ERR>>> Failed to create a file '${filePath}'`.red);
            } else {
              resolve();
            }
          });
        })
    );
  });

  return Promise.all(promises);
}

function getFiles(blockPath) {
  return new Promise((resolve, reject) => {
    fs.readdir(blockPath, (err, files) => {
      if (err) {
        reject(`ERR>>> Failed to get a file list from a folder '${blockPath}'`);
      } else {
        resolve(files);
      }
    });
  });
}

function printErrorMessage(errText) {
  console.log(errText);
  rl.close();
}

// //////////////////////////////////////////////////////////////////////////

function initMakeBlock(blockName) {
  const blockPath = path.join(BLOCKS_DIR, blockName);

  return validateBlockName(blockName)
    .then(() => directoryExist(blockPath, blockName))
    .then(() => createDir(blockPath))
    .then(() => createFiles(blockPath, blockName))
    .then(() => getFiles(blockPath))
    .then(files => {
      const line = '-'.repeat(48 + blockName.length);
      console.log(line);
      console.log(`The block has just been created in 'source/blocks/${blockName}'`);
      console.log(line);

      // Displays a list of files created
      files.forEach(file => console.log(file.yellow));

      rl.close();
    });
}


// //////////////////////////////////////////////////////////////////////////
//
// Start here
//

// Command line arguments
const blockNameFromCli = process.argv
    .slice(2)
    // join all arguments to one string (to simplify the capture user input errors)
    .join(' ');


// If the user pass the name of the block in the command-line options
// that create a block. Otherwise - activates interactive mode
if (blockNameFromCli !== '') {
  initMakeBlock(blockNameFromCli).catch(printErrorMessage);
}
else {
  rl.setPrompt('Block name: '.magenta);
  rl.prompt();
  rl.on('line', (line) => {
    const blockName = line.trim();
    initMakeBlock(blockName).catch(printErrorMessage);
  });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question