startService.js

/ 默认分类 / 0 条评论 / 173浏览

const os = require("os"); //获取本机ip function getIpAddress() { /**os.networkInterfaces() 返回一个对象,该对象包含已分配了网络地址的网络接口 */ var interfaces = os.networkInterfaces(); for (var devName in interfaces) { var iface = interfaces[devName]; for (var i = 0; i < iface.length; i++) { var alias = iface[i]; if ( alias.family === "IPv4" && alias.address !== "127.0.0.1" && !alias.internal ) { return alias.address; } } } } const myHost = getIpAddress();

var PORT = 8080; //端口 var types = { "css": "text/css", "gif": "image/gif", "html": "text/html", "ico": "image/x-icon", "jpeg": "image/jpeg", "jpg": "image/jpeg", "js": "text/javascript", "json": "application/json", "pdf": "application/pdf", "png": "image/png", "svg": "image/svg+xml", "swf": "application/x-shockwave-flash", "tiff": "image/tiff", "txt": "text/plain", "wav": "audio/x-wav", "wma": "audio/x-ms-wma", "wmv": "video/x-ms-wmv", "xml": "text/xml" }; var http = require('http'); var url = require('url'); var fs = require('fs'); var mine = types; var path = require('path');

var server = http.createServer(function (request, response) { // 解析请求,包括文件名 var pathname = url.parse(request.url).pathname; var realPath = pathname.substr(1); var ext = path.extname(realPath); ext = ext ? ext.slice(1) : 'unknown'; fs.exists(realPath, function (exists) { if (!exists) { response.writeHead(404, { 'Content-Type': 'text/plain' });

  response.write("This request URL " + pathname + " was not found on this server.");
  response.end();
} else {
  // console.log(realPath);
  fs.readFile(realPath, "binary", function (err, file) {
    if (err) {
      response.writeHead(500, {
        'Content-Type': 'text/plain'
      });
      response.end(err);
    } else {
      var contentType = mine[ext] || "text/plain";
      response.writeHead(200, {
        'Content-Type': contentType
      });
      response.write(file, "binary");
      response.end();
    }
  });
}

}); }); server.listen(PORT); console.log("服务启动成功,内网地址:\n" + myHost + ':' + PORT + "/laya/assets/index.html");

//读取所有ui.json,生成对应的接口类 //监听是否有文件发生变化,并出到bin目录 var fs = require('fs'); //读取所有json function getTs(child) { var a = ''; for (var i in child) { if (child[i].props.var) { if (child[i].props.name) a += '//' + child[i].props.name + '\n' a += '\t' + child[i].props.var + ':' + getObjType(child[i]) + ';\n'; } if (child[i].child) { a += getTs(child[i].child); } } return a; }

function getObjType(obj) { if (obj.props.runtime == "Script/FightingScript.ts") return 'FightingScript';

if (obj.props.runtime == "Script/BtnScript.ts")
    return 'BtnScript';

if (obj.props && obj.props.runtime) {
    return obj.props.runtime;
}
return "Laya." + obj.type;

}

// getAllJson('') function getJsonObj(obj) { let objNams = ['type', 'props', 'compId', 'child', 'runtime']; for (let i in obj) { if (objNams.indexOf(i) == -1) { delete obj[i]; } }

for (var i in obj.child) {
    let props = obj.child[i]['props'];
    let childType = obj.child[i]['type'];
    if (childType == 'Script') {
        let path = obj.child[i]['source'];
        let paths = path.split('/');
        paths.splice(0, 1);
        props['runtime'] = paths.join('/');
    }
    if (childType == 'SkeletonPlayer') {
        props['runtime'] = "Laya.Skeleton";
    }

    if (props['vScrollBarSkin']) {
        props['vScrollBarSkin'] = " ";
    }
    if (props['hScrollBarSkin']) {
        props['hScrollBarSkin'] = " ";
    }

    if (childType == 'Button') {
        if (props['stateNum'] || props['stateNum'] == 0) {
            props['stateNum'] = Number(props['stateNum']);
        }
    }
    if (childType == 'HTMLDivElement') {
        if (props['text']) {
            delete props['text']
        }
        if (props['fontSize']) {
            delete props['fontSize']
        }
    }


    if (childType == 'Label') {
        //Label 如果没有使用Text不包含的属性,就转换为Text
        let pInfos = ['left', 'right', 'top', 'bottom', 'centerX', 'centerY', 'anchorX', 'anchorY'];
        let isHanveInfo = false;
        for (let qqq in props) {
            if (pInfos.indexOf(qqq) != -1) {
                isHanveInfo = true;
                break;
            }
        }
    }
    if (childType == 'UIView') {
        let path = obj.child[i]['source'];
        let paths = path.split('/');
        // paths.splice(0, 1);
        paths = ["laya", "pages"].concat(paths);
        let runtime = paths[paths.length - 1];
        let runtimes = runtime.split(".");
        paths[paths.length - 1] = runtimes[0] + ".json";
        // runtime = paths.join('/');
        paths.splice(paths.length - 1, 1);
        let dirPath = paths.join("/");
        var a = fs.readdirSync(dirPath);
        if (a.indexOf(runtime) != -1) {
            // console.log(dirPath + "\\" + runtime);
            let target = fs.readFileSync(dirPath + "\\" + runtime);
            jsonObj = JSON.parse(target);
            // console.log(jsonObj.props.runtime);
            if (jsonObj.props.runtime) {
                childType = props["runtime"] = jsonObj.props.runtime;
            }
        }
    }
    if (childType != 'Text' &&
        childType != 'Sprite' &&
        childType != 'HTMLDivElement' &&
        childType != 'Text' &&
        childType != 'Text' &&
        childType != 'Text') {
        if (props['centerX'] || props['centerX'] == 0) {
            delete props['x']
        }

        if (props['centerY'] || props['centerY'] == 0) {
            delete props['y']
        }
    }

    if (props['skin']) {
        addLoadList(props['skin']);
    }
    if (props['texture']) {
        addLoadList(props['texture']);
    }
    if (props['styleSkin']) {
        addLoadList(props['styleSkin']);
    }

    let skin = props['skin'];
    if (skin && styles[skin]) {
        for (let q in styles[skin]) {
            if (!props[q] && props[q] != 0)
                props[q] = styles[skin][q];
        }

    }
    obj.child[i] = getJsonObj(obj.child[i]);
}
return obj;

} var loadList = []; function addLoadList(params) { if (loadList.indexOf(params) == -1) { loadList.push(params); } }

//把scene导出成json和d.ts function sceneToJsonAndDTs(path) { console.log('-----------'); console.log('处理' + path); let pathInfo = path.split('\'); pathInfo.splice(0, 2); var fsName = pathInfo.splice(pathInfo.length - 1, 1)[0]; var fsNames = fsName.split('.'); var jsonName = fsNames[0] + '.json'; let scencePath = pathInfo.join('\'); //导出json到bin目录 var a = fs.readFileSync(path); var b = a.toString(); var jsonObj; try { jsonObj = JSON.parse(b); loadList = []; jsonObj = getJsonObj(jsonObj); } catch (e) { console.log(e); console.error('导出json错误'); } jsonObj.loadList = loadList; jsonObj.loadList3D = []; for (let i = 0; i < pathInfo.length; i++) { let smallPath = 'laya/assets/' for (let q = 0; q < i; q++) { smallPath += pathInfo[q] + '/'; } let paths = fs.readdirSync(smallPath); if (paths.indexOf(pathInfo[i]) == -1) { fs.mkdirSync(smallPath + pathInfo[i]); } }

// jsonToTs(jsonObj, fsNames[0], scencePath, pathInfo)
fs.writeFileSync('laya\\assets\\' + scencePath + '\\' + jsonName, JSON.stringify(jsonObj));
// console.log('导出json成功');
//讲json更新到d.ts
var ts = 'interface I' + fsNames[0] + 'Ui extends Laya.' + jsonObj.type + '{\n' + getTs(jsonObj.child) + '}';
fs.writeFileSync('libs\\UI\\I' + fsNames[0] + 'Ui.d.ts', ts);
// console.log('导出d.ts成功');
var now = Date.now();
var dayTime = now % (24 * 60 * 60 * 1000);//小于1天的时间戳
var hTime = Math.floor(dayTime / (60 * 60 * 1000));//已经过了几个小时
var mTime = (dayTime - hTime * 60 * 60 * 1000) / (60 * 1000);//过了几分钟,带小数
var sTime = Math.floor(mTime % 1 * 60)
hTime += 8;
if (hTime < 10) hTime = '0' + hTime;
mTime = Math.floor(mTime);
if (mTime < 10) mTime = '0' + mTime;
console.log(hTime + ':' + mTime + ':' + sTime);
needAddPaths.shift();
if (needAddPaths.length) {
    sceneToJsonAndDTs(needAddPaths[0]);
}

}

function getProps(props) { let aaa = {}; let arr0 = props.split('@@!@@'); for (let i in arr0) { let arr1 = arr0[i].split('='); aaa[arr1[0]] = arr1[1]; } return aaa; }

var needAddPaths = []; var argvs = process.argv; var porjectPath = argvs[2]; console.log('porjectPath:' + porjectPath); const chokidar = require('chokidar'); function chokidarWatch() { chokidar.watch(".\laya\pages\").on('all', (event, path) => { if (event == 'add' || event == 'change') { if (needAddPaths.indexOf(".prefab") != -1) return; if (needAddPaths.indexOf(path) == -1) { needAddPaths.push(path); if (needAddPaths.length == 1) sceneToJsonAndDTs(path); } } }); }

var readXml = require('xmlreader'); // var a = fs.readFileSync('laya\styles.xml'); // var b = a.toString(); var styles = {}; // readXml.read(b, function (errors, xmlResponse) { // if (null !== errors) { // console.log(errors) // return; // } // var arr = xmlResponse.res.item.array; // for (let i in arr) { // let obj = arr[i].attributes(); // if (obj.props.indexOf('=') == -1) continue; // // console.log(obj.name); // let aaa = getProps(obj.props); // // console.log(aaa); // styles[obj.name] = aaa; // } // chokidarWatch(); // });

chokidarWatch();