Skip to content

Instantly share code, notes, and snippets.

@MrKou47
Last active November 25, 2017 08:15
Show Gist options
  • Save MrKou47/3c081057fddd56d87f86eb733dc22bf4 to your computer and use it in GitHub Desktop.
Save MrKou47/3c081057fddd56d87f86eb733dc22bf4 to your computer and use it in GitHub Desktop.
some code for minilize json file
/**
* 步骤
* 1. 先读取文件夹 再 读取所有的json文件
* 2. 再依次读取json内容
* 3. 替换文件中的内容
* 4. 写新的文件 到dist文件夹
*/
function minifyJson(rootPath) {
const saveDirName = 'dist';
const baseFolderName = path.basename(rootPath);
if (!fs.existsSync('dist')) {
fs.mkdirSync(saveDirName);
}
function mapFile(filePath) {
fs.readdir(filePath, (err, files) => {
if (err) return new Error(err);
files.forEach(file => {
const tempPath = path.join(filePath, file);
const isDir = fs.statSync(tempPath).isDirectory();
if (isDir) {
return mapFile(tempPath);
} else {
minify(tempPath);
}
});
});
}
function minify(filePath) {
fs.readFile(filePath, { encoding: 'utf8' }, (err, data) => {
if (err) return new Error(err);
const miniData = data.replace(/[\s\n]+/ig, '');
const pathObj = path.parse(filePath);
pathObj.dir = pathObj.dir.replace(baseFolderName, saveDirName);
pathObj.name = `${pathObj.name}.min`;
if (!fs.existsSync(pathObj.dir)) {
fs.mkdirSync(pathObj.dir);
}
fs.writeFile(path.format(pathObj), miniData, { encoding: 'utf8' }, (err) => {
if (err) return new Error(err);
log(filePath);
});
});
}
function log(filePath) {
fs.appendFile('minify.log', `${new Date()}: minify [${filePath}] success.\n`, err => {
if (err) return new Error(err);
});
}
mapFile(rootPath);
}
// how to use
minifyJson(path.join(__dirname, 'test-folder'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment