How to use get-port - 10 common examples

To help you get started, we’ve selected a few get-port examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github microsoft / vscode-js-debug / src / int-chrome / puppeteer / launchPuppeteer.ts View on Github external
public static async start(
    debugClient: ExtendedDebugClient,
    daConfig: IScenarioConfiguration,
    chromeArgs: string[] = [],
    callbacks: IDebugAdapterCallbacks,
  ): Promise {
    const daPort = await getPort();
    // logger.log(`About to ${daConfig.scenario} debug-adapter at port: ${daPort}`); // TODO@rob

    let browser: Browser;
    if (daConfig.scenario === 'launch') {
      await launchTestAdapter(
        debugClient,
        Object.assign({}, daConfig, { runtimeArgs: [`--remote-debugging-port=${daPort}`] }),
        callbacks,
      );
      browser = await connectPuppeteer(daPort);
    } else {
      browser = await launchPuppeteer(daPort, chromeArgs);

      // We want to attach after the page is fully loaded, and things happened, to simulate a real attach scenario. So we wait for a little bit
      await utils.promiseTimeout(undefined, 1000);
github pnpm / pnpm / packages / pnpm / src / cmd / server / start.ts View on Github external
async function getTcpOptions () {
    return {
      hostname: 'localhost',
      port: opts.port || await getPort({ port: 5813 }), // tslint:disable-line
    }
  }
github zeit / now / packages / now-static-build / src / index.ts View on Github external
meta.isDev &&
      (devCommand ||
        (pkg && devScript && pkg.scripts && pkg.scripts[devScript]))
    ) {
      let devPort: number | undefined = nowDevScriptPorts.get(entrypoint);

      if (typeof devPort === 'number') {
        debug(
          '`%s` server already running for %j',
          devCommand || devScript,
          entrypoint
        );
      } else {
        // Run the `now-dev` or `dev` script out-of-bounds, since it is assumed that
        // it will launch a dev server that never "completes"
        devPort = await getPort();
        nowDevScriptPorts.set(entrypoint, devPort);

        const opts: SpawnOptions = {
          cwd: entrypointDir,
          stdio: 'inherit',
          env: { ...spawnOpts.env, PORT: String(devPort) },
        };

        const cmd = devCommand || `yarn run ${devScript}`;
        const child: ChildProcess = spawnCommand(cmd, opts);

        child.on('exit', () => nowDevScriptPorts.delete(entrypoint));
        nowDevChildProcesses.add(child);

        // Now wait for the server to have listened on `$PORT`, after which we
        // will ProxyPass any requests to that development server that come in
github elastic / kibana / x-pack / plugins / code / server / lsp / java_launcher.ts View on Github external
public async launch(builtinWorkspace: boolean, maxWorkspace: number, installationPath: string) {
    let port = 2090;

    if (!this.options.lsp.detach) {
      port = await getPort();
    }
    const log = this.loggerFactory.getLogger(['code', `java@${this.targetHost}:${port}`]);
    const proxy = new LanguageServerProxy(port, this.targetHost, log, this.options.lsp);
    proxy.awaitServerConnection();
    if (this.options.lsp.detach) {
      // detach mode
      proxy.onConnected(() => {
        this.isRunning = true;
      });
      proxy.onDisconnected(() => {
        this.isRunning = false;
        if (!proxy.isClosed) {
          proxy.awaitServerConnection();
        }
      });
    } else {
github prisma / lift / src / Studio.ts View on Github external
throw new Error(
          `Could not find any Prisma2 query-engine binary for Studio. Looked in ${pathCandidates.join(', ')}`,
        )
      }

      const StudioServer = (await import('@prisma/studio-server')).default

      let photonWorkerPath: string | undefined
      try {
        const studioTransport = require.resolve('@prisma/studio-transports')
        photonWorkerPath = path.join(path.dirname(studioTransport), 'photon-worker.js')
      } catch (e) {
        //
      }

      this.port = await getPort({ port: getPort.makeRange(5555, 5600) })
      this.instance = new StudioServer({
        port: this.port,
        debug: false,
        binaryPath: firstExistingPath.path,
        photonWorkerPath,
        photonGenerator: {
          version: packageJson.prisma.version,
          providerAliases,
        },
        schemaPath: getDatamodelPath(this.projectDir),
        // reactAppDir: path.join(path.dirname(require.resolve('@prisma/studio/package.json')), 'build'),
      })

      await this.instance.start()

      return `Studio started at http://localhost:${this.port}`
github ipfs-shipyard / ipfs-companion / add-on / src / lib / ipfs-client / embedded-chromesockets.js View on Github external
dht: {
        // TODO: check if below is needed after js-ipfs is released with DHT disabled
        enabled: false
      }
    }
  }
  const userOpts = JSON.parse(opts.ipfsNodeConfig)
  const ipfsNodeConfig = mergeOptions.call({ concatArrays: true }, defaultOpts, userOpts, { start: false })

  // Detect when API or Gateway port is not available (taken by something else)
  // We find the next free port and update configuration to use it instead
  const multiaddr2port = (ma) => parseInt(new URL(multiaddr2httpUrl(ma)).port, 10)
  const gatewayPort = multiaddr2port(ipfsNodeConfig.config.Addresses.Gateway)
  const apiPort = multiaddr2port(ipfsNodeConfig.config.Addresses.API)
  log(`checking if ports are available: api: ${apiPort}, gateway: ${gatewayPort}`)
  const freeGatewayPort = await getPort({ port: getPort.makeRange(gatewayPort, gatewayPort + 100) })
  const freeApiPort = await getPort({ port: getPort.makeRange(apiPort, apiPort + 100) })
  if (gatewayPort !== freeGatewayPort || apiPort !== freeApiPort) {
    log(`updating config to available ports: api: ${freeApiPort}, gateway: ${freeGatewayPort}`)
    const addrs = ipfsNodeConfig.config.Addresses
    addrs.Gateway = addrs.Gateway.replace(gatewayPort.toString(), freeGatewayPort.toString())
    addrs.API = addrs.API.replace(apiPort.toString(), freeApiPort.toString())
  }

  return ipfsNodeConfig
}
github himynameisdave / svb / lib / rollup.js View on Github external
const getPlugins = async ({
  input,
  output,
  isDevelopmentMode,
}) => {
  const inputFolder = path.dirname(input);
  const port = await getPort({
    port: getPort.makeRange(3000, 3100),
  });
  return isDevelopmentMode
    //  Dev plugins
    ? [
      sourcemaps(),
      serve({
        // Launch in browser
        open: true,
        contentBase: output,
        port,
        verbose: true,
      }),
      livereload({
        watch: [
          output,
          inputFolder,
github microsoft / vscode-java-test / src / runners / junit5Runner / JUnit5Runner.ts View on Github external
protected async launchTests(launchConfiguration: DebugConfiguration): Promise {
        const commandParams: string[] = [];
        if (launchConfiguration.vmArgs) {
            commandParams.push(...launchConfiguration.vmArgs);
        }

        const javaDebugPort: number = await getPort();
        if (!launchConfiguration.noDebug) {
            commandParams.push('-Xdebug', `-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=${javaDebugPort}`);
        }

        if (launchConfiguration.encoding) {
            commandParams.push(`-Dfile.encoding=${launchConfiguration.encoding}`);
        }

        if (launchConfiguration.classPaths) {
            this.storagePathForCurrentSession = path.join(this.storagePath || os.tmpdir(), new Date().getTime().toString());
            commandParams.push('-cp', await classpathUtils.getClassPathString(launchConfiguration.classPaths, this.storagePathForCurrentSession));
        }

        if (launchConfiguration.mainClass) {
            commandParams.push(launchConfiguration.mainClass);
        }
github process-engine / bpmn-studio / electron_app / electron.ts View on Github external
const devUserDataFolderPath = path.join(__dirname, '..', 'userData');
  const prodUserDataFolderPath = app.getPath('userData');

  const userDataFolderPath = releaseChannel.isDev() ? devUserDataFolderPath : prodUserDataFolderPath;

  if (!releaseChannel.isDev()) {
    process.env.CONFIG_PATH = path.join(__dirname, '..', '..', '..', 'config');
  }

  const configForGetPort = {
    port: getPortListByVersion(releaseChannel.getVersion()),
    host: '0.0.0.0',
  };
  console.log('Trying to start internal ProcessEngine on ports:', configForGetPort);

  const port = await getPort(configForGetPort);

  console.log(`Internal ProcessEngine starting on port ${port}.`);

  process.env.http__http_extension__server__port = `${port}`;

  const processEngineDatabaseFolderName = getProcessEngineDatabaseFolderName();

  process.env.process_engine__process_model_repository__storage = path.join(
    userDataFolderPath,
    processEngineDatabaseFolderName,
    'process_model.sqlite',
  );
  process.env.process_engine__flow_node_instance_repository__storage = path.join(
    userDataFolderPath,
    processEngineDatabaseFolderName,
    'flow_node_instance.sqlite',
github opticdev / optic / api-cli / src / commands / spec.ts View on Github external
const specFileExists = await fs.pathExists(specStorePath)

    if (specFileExists) {
      try {
        const specFileContents = await fs.readJson(specStorePath)
        if (!Array.isArray(specFileContents)) {
          throw new Error('not array')
        }
      } catch (e) {
        return this.error(fromOptic('It looks like there is something wrong with your API spec file. Please make sure it is a valid JSON array.'))
      }
    }

    await emitGitState()

    const port = await getPort({port: getPort.makeRange(3201, 3299)})
    const sessionUtilities = new SessionUtilities(sessionsPath)
    const sessionValidatorAndLoader = new FileSystemSessionValidatorAndLoader(sessionUtilities)
    const paths = await getPaths()
    await startServer(paths, sessionValidatorAndLoader, port, config)

    const url = `http://localhost:${port}/`
    this.log(fromOptic('Displaying your API Spec at ' + url))
    await open(url)
    await cli.wait(1000)
    await cli.anykey('Press any key to exit')
    return process.exit()
  }
}

get-port

Get an available port

MIT
Latest version published 9 months ago

Package Health Score

77 / 100
Full package analysis