-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
50 lines (49 loc) · 1.81 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/****************************************************
* author: hualei
* time: 2012/12/25 13:20:20
* fileName:index.js
*****************************************************/
var fs = require('fs'),
path = require('path');
var ptpl = {
init: function (arg) {
var arg = arg || 'ptpl-text!';
this.flag = arg;
this.readFiles();
},
readFiles: function () {
var that = this;
var dir = '.'; // 在当前目录下操作
var search = function (dir) {
try {
var files = fs.readdirSync(dir);
files.forEach(function (file, index) {
var dpath = path.normalize(dir + '/' + file);
var stats = fs.statSync(dpath);
if (stats.isFile()) {
if (path.extname(dpath) === '.js') {
that.parse(dir, dpath);
}
} else if (stats.isDirectory()) {
search(dpath);
}
});
} catch (err) { }
};
search(dir);
},
parse: function (dir, file) {
var data = fs.readFileSync(file, 'utf8');
var reg = new RegExp('<!--' + this.flag + '(.*?(.html|.htm|.tpl))-->', 'g');
while ((arr = reg.exec(data)) && arr.length == 3) {
var tpl = fs.readFileSync(path.resolve(dir, arr[1]), 'utf8');
tpl = tpl.replace(/\r*\n\s*/igm, '').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var rep = new RegExp("'\\s*" + arr[0] + "[^']*'");
//console.log(rep.exec(data)[0]);
data = data.replace(rep.exec(data)[0], "'" + arr[0] + tpl + "'");
fs.writeFileSync(file, data);
console.log('parse file success');
}
}
}
exports.ptpl = ptpl;