aozhiwei bbf298ce4b 1
2022-03-29 07:58:30 +08:00

123 lines
2.5 KiB
JavaScript

const fs = require('fs');
const events = require('events');
const serverEnv = process.env['SERVER_ENV'];
const event = new events.EventEmitter();
function rspErr(rsp, errCode, errMsg) {
rsp.send(jsonEncode({
'errcode': errCode,
'errmsg': errMsg
}));
}
function rspOk(rsp) {
rsp.send(jsonEncode({
'errcode': 0,
'errmsg': ''
}));
}
function rspData(rsp, data) {
data['errcode'] = 0;
data['errmsg'] = '';
rsp.send(jsonEncode(data));
}
function readJsonFromFile(url) {
const jsondata = fs.readFileSync(url, "utf8");
const json = JSON.parse(jsondata);
return json;
}
async function sleep(timeout) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve();
}, timeout);
});
}
function emptyReplace(val, newVal) {
return !val ? newVal : val;
}
function throwError(msg) {
console.log(msg);
throw msg;
}
function isOnlineEnv() {
return !serverEnv;
}
function isTestEnv() {
return serverEnv == 'TEST';
}
function getUtcTime() {
return Math.floor((new Date()).getTime() / 1000);
}
function formatDate(date) {
const year = date.getFullYear();
const month = date.getMonth() + 1;//月份是从0开始的
const day = date.getDate();
const hour = date.getHours();
const min = date.getMinutes();
const sec = date.getSeconds();
return year + '-' +
(month < 10 ? '0' + month : month) + '-' +
(day < 10 ? '0' + day : day) + ' ' +
(hour < 10 ? '0' + hour : hour) + ':' +
(min < 10 ? '0' + min : min) + ':' +
(sec < 10 ? '0' + sec : sec);
}
function pad(num, n) {
let result = num.toString();
let len = result.length;
while (len < n) {
result = '0' + result;
len++;
}
return result;
}
function registerEventHandler(eventName, handler) {
event.on(eventName, handler);
}
function emitEvent(eventName, ...args) {
event.emit(eventName, ...args);
}
function randRange(min, max) {
if (min >= max) {
return min;
}
return min + Math.random() * max;
}
function jsonEncode(obj) {
return JSON.stringify(obj);
}
exports.rspErr = rspErr;
exports.rspOk = rspOk;
exports.rspData = rspData;
exports.readJsonFromFile = readJsonFromFile;
exports.sleep = sleep;
exports.emptyReplace = emptyReplace;
exports.throwError = throwError;
exports.isOnlineEnv = isOnlineEnv;
exports.isTestEnv = isTestEnv;
exports.getUtcTime = getUtcTime;
exports.formatDate = formatDate;
exports.pad = pad;
exports.registerEventHandler = registerEventHandler;
exports.emitEvent = emitEvent;
exports.randRange = randRange;
exports.jsonEncode = jsonEncode;