通过bat命令调用nodejs 执行js文件,从而来改变注释。
通常,我们写代码的时候,习惯简化,用“//”,而不习惯用“/** XXX */”(当然快捷方式除外)
下面就通过BAT命令,把文件拖入BAT命令来执行转换,当前主要针对js, ts。来处理。要改成其它也是很容易的。
具体处理方式如下:
1:任意文件拖入bat命令,从而获取文件名:
@echo off
set str=%*
set "str=%str:"=%"
set "str= %str%"
call set "str=%%str: %~d1=" "%~d1%%"
node C:\Users\Administrator\Desktop\清理文件\注释转换工具\AnnotationConversionTool.js "%str%"
pause
2:AnnotationConversionTool.js:
用nodejs 进行注释转换,具体代码如下:
console.log("start");
console.log(process.argv);
var fs = require(‘fs‘);
/** [ */
/** ‘C:\\Program Files\\nodejs\\node.exe‘, */
/** ‘C:\\Users\\Administrator\\Desktop\\a.js‘, */
/** ‘‘, */
/** ‘C:\\Users\\Administrator\\Desktop\\新建文件夹‘ */
/** ] */
const args = process.argv;
for (let i = 0; i < args.length; i++) {
const path = args[i];
if (path == "" || path.indexOf("node.exe") > -1 || path.indexOf("AnnotationConversionTool.js") > -1) {
continue;
}
if (path.indexOf(".") < 0) {
checkDirDescription(path);
} else {
checkFileDescription(path);
}
}
function checkDirDescription(path) {
var files = fs.readdirSync(path);
for (var index = 0; index < files.length; index++) {
var file = files[index];
console.log("file name: " + file);
const filePath = path + ‘/‘ + file;
var states = fs.statSync(filePath);
if (!states.isDirectory() && (file.substr(file.lastIndexOf(‘.‘) + 1) == "ts" || file.substr(file.lastIndexOf(‘.‘) + 1) == "js") && file.indexOf("~") < 0) {
checkFileDescription(filePath);
console.log("file: " + filePath);
} else {
if (states.isDirectory()) {
checkDirDescription(filePath);
console.log("dir: " + filePath);
}
}
}
}
function checkFileDescription(path) {
if (path.indexOf(".meta") > -1) {
return;
}
console.log("path: " + path);
var data = fs.readFileSync(path, "utf-8");
/** console.log(data); */
console.log(data.length);
const list = data.split("\n")
let newList = [];
for (let index = 0; index < list.length; index++) {
const line = list[index];
console.log(line);
if (line.indexOf("//") < 0 || line.indexOf("//////") > -1) {
newList.push(line);
continue;
}
const elements = line.split("//");
const leftStr = elements[0];
const rightStr = elements[1].split("\r")[0];
if (leftStr < 1 || leftStr.trim().length < 1) {
//console.log(elements[0]);
const newLine = elements[0] + "/** " + rightStr + " */\r";
newList.push(newLine);
//console.log(newLine);
} else {
const nl = getPreWhiteSpace(leftStr) + "/** " + rightStr + " */\r";
newList.push(nl);
// console.log(nl);
newList.push(elements[0]);
// console.log(elements[0]);
}
}
const newData = newList.join("\n");
fs.writeFile(path, newData, ‘utf8‘, (err) => {
if (err) throw err;
console.log(‘success done‘);
});
console.log(newData);
}
function getPreWhiteSpace(line) {
let preLine = "";
const length = line.length;
const signs = line.split("");
for (let i = 0; i < signs.length; i++) {
const sign = signs[i];
if (sign == " ") {
preLine += " ";
} else {
break;
}
}
return preLine;
}
console.log("end");
注意点:
1:bat命令保存方式用ansi,不用utf8,以此来可以读取中文路径。
2:bat里的js路径要改成js真实路径,不然调用不到。