mkfiles
Version:
Batch create module directories and files!
139 lines (120 loc) • 3.36 kB
JavaScript
/**
* @fileoverview make files in the specified directory
*/
var fs = require('fs');
var mkdirp = require('mkdirp');
var handlebars = require('handlebars');
var colors = require('colors');
/**
* Whether a string is end of the specified character
* @param str {String} target string
* @param suffix {String} the specified character
* @return {Boolean}
* @private
*/
function endsWith(str, suffix) {
return str.substring(str.length - 1) == suffix;
}
/**
* If the path is not end of '/', then add it.
* @param path {String} target path
* @return {String}
* @private
*/
function formatPath(path) {
path = path.trim();
return endsWith(path, '/') ? path : (path + '/');
}
/**
* create dir
* @param opt the same as the exports method
* @return void
* @private
*/
function createDirs(opt) {
var path = formatPath(opt.path);
var dirs = opt.dirs;
var files = opt.files;
dirs = Array.isArray(dirs) ? dirs : [dirs || ''];
dirs.forEach(function(dir) {
if (typeof dir !== 'string') {
throw new Error('The dir name must me string !');
}
var curDirPath = path + dir;
if (!fs.existsSync(curDirPath)) {
mkdirp.sync(curDirPath);
console.log('Creating ' + curDirPath + colors.green(' OK'));
} else {
console.log(colors.yellow('Warning: ' + curDirPath + ' already exists, skipped !'));
}
createFiles({
path: curDirPath,
files: files
});
});
}
/**
* create files in the specified dir
* @param opt the same as the exports method
* @return void
* @private
*/
function createFiles(opt) {
var curDirPath = opt.path;
var files = opt.files;
if (!Array.isArray(files)) {
throw new Error('The "files" field must be array !');
}
files.forEach(function(curFile) {
var oFile = (typeof curFile === 'object' && curFile.file) ? curFile : {
file: curFile,
content: ''
};
var filePath = formatPath(curDirPath) + oFile.file;
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, getFileContent(oFile.content));
console.log('Creating ' + filePath + colors.green(' OK'));
} else {
console.log(colors.yellow('Warning: ' + filePath + ' already exists, skipped !'));
}
});
}
/**
* get file content
* @param cfg {String|Object}
* @param cfg {String} file content
* @param cfg {Object}
* {
* template: {String}, 'template file path' || 'template content'
* data: {Object}
* }
* @return output {String}
* @private
*/
function getFileContent(cfg) {
var output;
var template = cfg.template;
if (typeof cfg === 'string') {
output = cfg;
} else if (typeof cfg === 'object') {
template = fs.existsSync(template) ? fs.readFileSync(template, 'utf8') : template;
output = handlebars.compile(template)(cfg.data);
} else {
output = '';
}
return output;
}
/**
* @param opt {Object|Array}
* {
* path: '',
* dirs: 'directory name',
* files: ['filename' || {file: 'filename', content: 'default file content'}]
* }
* @return void
* @public
*/
module.exports = function(opt) {
opt = Array.isArray(opt) ? opt : [opt];
opt.forEach(createDirs);
};