mihawk
Version:
A tiny & simple mock server tool, support json,js,cjs,ts(typescript).
62 lines (61 loc) • 2.2 kB
JavaScript
;
import net from 'net';
import os from 'os';
import Colors from 'color-cc';
import { Printer } from './print';
export async function detectPort(port, noLogPrint) {
const result = (await new Promise(res => {
const server = net.createServer().listen(port);
server.on('listening', function () {
server.close();
res({ isInUse: false, err: null });
});
server.on('error', (err) => {
const ERR_CODE = err.code.toUpperCase();
if (ERR_CODE === 'EADDRINUSE') {
!noLogPrint && Printer.error(Colors.yellow(`[ERROR] ${port} 端口占用中!`));
}
if (ERR_CODE === 'EACCES') {
!noLogPrint && Printer.error(Colors.yellow(`[ERROR] ${port} 端口访问受限制!`));
}
res({ isInUse: true, err: err });
});
}));
return result;
}
export async function isPortInUse(port, options) {
const { timeout = 1000, noLogPrint = false } = options || {};
let isInUse = false;
try {
const detectd = await Promise.race([
detectPort(port, !!noLogPrint),
new Promise(res => setTimeout(() => res({ err: `Timeout with ${timeout}` }), parseInt(timeout) || 1000)),
]);
isInUse = !!detectd?.isInUse;
}
catch (error) {
Printer.warn(Colors.warn(`Detec isPortInUse(${port}) occur errors:`), error);
isInUse = false;
}
return isInUse;
}
export function getMyIp(ipv6 = false) {
const LOCAL_HOST = '127.0.0.1';
const PROTOCOL = ipv6 ? 'ipv6' : 'ipv4';
const interfaces = os.networkInterfaces();
for (const infoList of Object.values(interfaces)) {
for (const info of infoList) {
const { address, family, internal, } = info || {};
if (address !== LOCAL_HOST && !internal && family.toLowerCase() === PROTOCOL) {
return address;
}
}
}
return LOCAL_HOST;
}
export function isLocalHost(host) {
return host === 'localhost' || host === '127.0.0.1' || host === '::1';
}
export function supportLocalHost(host) {
return isLocalHost(host) || '0.0.0.0' === host;
}