global-time
Version:
Gets UTC real time from http://worldtimeapi.org/api/timezone/Etc/UTC.
33 lines (32 loc) • 1.16 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_fetch_1 = __importDefault(require("node-fetch"));
const url = 'http://worldtimeapi.org/api/timezone/Etc/UTC';
let ip;
async function globalTime() {
let obj;
try {
obj = await node_fetch_1.default(url).then(e => e.json());
}
catch (e) {
if (e.code === 'ENOTFOUND') {
throw new Error(`"${url}" is currently unavailable.`);
}
else if (e.type === 'invalid-json') {
throw new Error(`Too many requests for "${url}"${ip ? ` from ip "${ip}"` : ''}. Try a bit later.`);
}
throw e;
}
ip = obj.client_ip;
const [, tail = ''] = obj.utc_datetime.match(/:\d+.\d{3}(\d*)\+/) || [];
const time = +`${+new Date(obj.utc_datetime)}.${tail}`;
return time;
}
exports.default = globalTime;
if (typeof exports.default === 'function') {
module.exports = exports.default;
Object.assign(module.exports, exports);
}