Node抽取Spring的控制器

Usage


node app.js 读取路径 [写入文件路径(default:./api.txt)]

Output

OrgAction.java
    /org/index/{pk_org}
    /org/save
UserAction.java
    /user/index/{pk_user}
    /user/delete

app.js

var fs = require('fs'),
    readline = require('readline');

var writePath = './api.txt', // 写入路径
    readPath =  null, // 读取路径
        classReq = null, // 类请求映射
        flag = null; // 控制一个Action只取一次classReq

var args = process.argv.splice(2);
if(!args[0]) {
    throw new Error('请配置"读取路径"参数!eg:node app.js readPath');
} else {
    readPath = args[0];
    if(args[1]) {
        writePath = args[1];
    }
    console.log("读取路径:" + readPath);
    console.log("写入文件:" + writePath);
}

// 写入文件
var write = function(data) {
    // 同步
    fs.writeFileSync(writePath, data, {flag: 'a'});

    // 异步
    // fs.writeFile(writePath, data, {flag: 'a'}, function (err) {
    //  if(err) {
    //      console.log(err);
    //  }
    // })
}

// 读取文件,抽取@RequestMapping("xxx")
var read = function(filePath, fileName) {
    var rl = readline.createInterface({
        input: fs.createReadStream(filePath), 
        output: process.stdout,
        terminal: false
    });

    rl.on('line', function(line){
        if(line.match(/@RequestMapping(.+)/)) {
            var m = line.match(/".+"/);
            if(m) {
                var req = m[0].replace(/"/g, '');
                // 默认"类请求映射"没有value且只取一次
                // flag 用于防止"方法请求映射"没有value
                if(!flag || flag !== fileName) {
                    flag = fileName;
                    if(line.indexOf('value') === -1) {
                        classReq = req;
                        if(!classReq.endsWith("/")) {
                            classReq += "/";
                        }
                        write(fileName + '\r\n');
                    }
                } else {
                    write('\t'+ classReq + req + '\r\n');
                }
            } else if(classReq && flag === fileName) {
                // 如果没有方法请求映射,取类请求映射
                write('\t'+ classReq + '\r\n');
            } else {
                // 错误信息
                console.error(fileName + ':' + line);
            }
        }
    });
}

// 循环读取
var loop_Read = function(path) {
    fs.readdir(path, function(err, files) {
        if(err) {
            throw new Error('读取文件出错!文件路径:' + path);
        }
        files.forEach(function(fileName) {
            var filePath = path + '\\' + fileName;
            if(fs.statSync(filePath).isDirectory()) {
                loop_Read(filePath);
            } else {
                if(fileName.match(/.+Action.java$/)) {
                    read(filePath, fileName);
                }
            }
        })
    })
}

// 创建/清空文件
fs.writeFile(writePath, '', {flag: 'w'}, function (err) {
    if(err) {
        throw new Error('写入路径不存在!');
    }
    loop_Read(readPath);
})

你可能感兴趣的:(Node抽取Spring的控制器)