Skip to content

Commit

Permalink
f
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Dec 10, 2024
1 parent f6ce4d8 commit 687a374
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 7 deletions.
30 changes: 23 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,24 +42,40 @@
npm i detect-port
```

CommonJS

```javascript
const detect = require('detect-port');
/**
* use as a promise
*/
const { detect } = require('detect-port');

detect(port)
.then(_port => {
if (port == _port) {
.then(realPort => {
if (port == realPort) {
console.log(`port: ${port} was not occupied`);
} else {
console.log(`port: ${port} was occupied, try port: ${_port}`);
console.log(`port: ${port} was occupied, try port: ${realPort}`);
}
})
.catch(err => {
console.log(err);
});
```

ESM and TypeScript

```ts
import { detect } from 'detect-port';

detect(port)
.then(realPort => {
if (port == realPort) {
console.log(`port: ${port} was not occupied`);
} else {
console.log(`port: ${port} was occupied, try port: ${realPort}`);
}
})
.catch(err => {
console.log(err);
});
```

## Command Line Tool
Expand Down
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,7 @@ import { detectPort } from './detect-port.js';
export default detectPort;

export * from './detect-port.js';
// keep alias detectPort to detect
export const detect = detectPort;

export * from './wait-port.js';
9 changes: 9 additions & 0 deletions test/detect-port.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { strict as assert } from 'node:assert';
import { ip } from 'address';
import mm from 'mm';
import { detectPort } from '../src/detect-port.js';
import detect from '../src/index.js';
import { detect as detect2 } from '../src/index.js';

describe('test/detect-port.test.ts', () => {
afterEach(mm.restore);
Expand Down Expand Up @@ -74,6 +76,13 @@ describe('test/detect-port.test.ts', () => {
assert(port >= 1024 && port < 65535);
});

it('should detect work', async () => {
let port = await detect();
assert(port >= 1024 && port < 65535);
port = await detect2();
assert(port >= 1024 && port < 65535);
});

it('with occupied port, like "listen EACCES: permission denied"', async () => {
const port = 80;
const realPort = await detectPort(port);
Expand Down

0 comments on commit 687a374

Please sign in to comment.