jmms
Version:
Jmms cli tools, Jmms is a java meta-micro-service framework
96 lines (85 loc) • 2.18 kB
JavaScript
const _ = require('lodash');
const chalk = require('chalk');
const metas = require('./metas');
const log = require('./log');
const path = require('path');
const net = require('net');
const fs = require('fs');
const yaml = require('js-yaml');
/**
* @param {*} mod The module of generator.
*/
const resolveMeta = (mod) => {
const a = path.dirname(mod.filename).split(path.sep);
var meta = metas[a[a.length-1]];
if(!meta) {
meta = metas[a[a.length-2] + ':' + a[a.length-1]];
}
return meta;
}
const copyProperties = (from, to) => {
Object.keys(from).forEach((key) => {
to[key] = from[key];
});
}
const checkPort = (port, callback) => {
const server = net.createServer();
server.unref();
server.on('error', () => {
log.error('Port ' + port + ' is being used, please free it and run again!');
process.exit(0);
});
server.listen({port: port}, () => {
server.close(() => {
callback.call(this);
});
});
}
const checkPorts = (ports, callback) => {
checkPortIndex(ports, 0, callback);
}
const checkPortIndex = (ports, index, callback) => {
if(!index) {
index = 0;
}else if(index == ports.length) {
callback.call(this);
return;
}
checkPort(ports[index], () => {
checkPortIndex(ports, index + 1, callback);
})
}
const existsJsonOrYaml = (pathWithoutExt) => {
const exts = ['.json', '.yaml', '.yml'];
for(var ext of exts) {
const file = pathWithoutExt + ext;
if(fs.existsSync(file)) {
return file;
}
}
return null;
}
const loadJsonOrYaml = (pathWithoutExt) => {
const file = existsJsonOrYaml(pathWithoutExt);
if(null == file) {
return null;
}else {
return loadJsonOrYamlFile(file);
}
}
const loadJsonOrYamlFile = (file) => {
if(file.endsWith('.json')) {
return require(file);
}else {
return yaml.safeLoad(fs.readFileSync(file, 'utf-8'));
}
}
module.exports = {
resolveMeta,
copyProperties,
checkPort,
checkPorts,
existsJsonOrYaml,
loadJsonOrYaml,
loadJsonOrYamlFile
}