text: 'use strict';
  
  const net = require('net');
  const fsMemo = require('fs-memo');
  
  const defaults = {
    name: "default",
    random: false,
    port: parseInt(process.env.PORT || "") || 3e3,
    ports: [4e3, 5e3, 6e3, 7e3],
    memoName: "port"
  };
  async function getPort(config) {
    const options = {...defaults, ...config};
    const portsToCheck = [];
    if (!options.random) {
      if (options.port) {
        portsToCheck.push(options.port);
      }
      if (Array.isArray(options.ports)) {
        portsToCheck.push(...options.ports);
      }
    }
    const memoOptions = {name: options.memoName, dir: options.memoDir};
    const memoKey = "port_" + options.name;
    const memo = await fsMemo.getMemo(memoOptions);
    if (memo[memoKey]) {
      portsToCheck.push(memo[memoKey]);
    }
    const availablePort = await checkPorts(portsToCheck);
    await fsMemo.setMemo({[memoKey]: availablePort}, memoOptions);
    return availablePort;
  }
  async function checkPorts(ports) {
    for (const p of ports) {
      const r = await checkPort(p);
      if (r) {
        return r;
      }
    }
    return checkPort(0);
  }
  function checkPort(port) {
    return new Promise((resolve) => {
      const server = net.createServer();
      server.unref();
      server.on("error", () => {
        resolve(false);
      });
      server.listen({port}, () => {
        const {port: port2} = server.address();
        server.close(() => {
          resolve(port2);
        });
      });
    });
  }
  
  module.exports = getPort;
  