Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow a validation function #60

Open
Richienb opened this issue Nov 20, 2021 · 3 comments
Open

Allow a validation function #60

Richienb opened this issue Nov 20, 2021 · 3 comments

Comments

@Richienb
Copy link
Contributor

Instead of checking if a file exists, we just try to open it.
So, instead of searching for a port, try to use the port and try another if it fails.

So, for example:

import express from 'express';
import {getValidatedPort} from 'get-port';
import pDefer from 'p-defer';

const app = express();

function listen(port) {
	const {promise, resolve, reject} = pDefer();

	app
		.listen(port, () => {
			app.off('error', reject);
			resolve();
		})
		.on('error', reject);

	return promise;
}

await getValidatedPort(listen);

What should the getValidatedPort function return? If we return the port that is used, we can't access the return value of the validation function and vice versa.

How should we check if the validator function approves an option? In the example, we check for a resolved or rejected promise but we could instead be checking for a boolean value.

@sindresorhus
Copy link
Owner

sindresorhus commented Jan 6, 2022

What problem does this solve? The current way of getting ports is working fine for me, so not sure how this makes it better.

@Richienb
Copy link
Contributor Author

Richienb commented Jan 7, 2022

Cross-process race conditions can be avoided by trying to use the port as part of the validation check. For example, when starting an express server, you could try opening it on a specific port directly and reacting to the errors instead of first checking if it's free and then opening it where some other script could take the port in the meantime.

@sindresorhus
Copy link
Owner

It is actually possible to reserve a port, and the kernel will then ensure it's not taken by other processes. I think the best first course of action would be to open a Node.js issue requesting an API for this.

Specifically, the C bind() function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants