Skip to content

Commit

Permalink
feat(listen() & shutdown() methods): Optional callbacks were adde…
Browse files Browse the repository at this point in the history
…d to these 2 methods

Optional callbacks were added to `listen()` & `shutdown()` methods to consumer be able to handle
events even without `then()` method.
  • Loading branch information
mirismaili committed Jun 29, 2019
1 parent 33c85c2 commit b2d82e7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,11 @@ npm install simplatic-http-server
const staticServer = new StaticServer(portNumber /*, servePath = process.cwd() */)
```

3. Listen to a port:
3. Listen to `portNumber`:

```js
await staticServer.listen()
await staticServer.listen(/* onListenCallback, onErrorCallback */)

console.log(`The static server listening on ${portNumber} ...`)
```

Expand All @@ -85,10 +86,10 @@ npm install simplatic-http-server
)
```

4. Get access to a file in `servePath`. E. g: type in your browser's address bar: `http://127.0.0.1/dir/index.html`. *Note: The path of `index.html` must be `` `${servePath}/dir/index.html` `` on your local machine.*
4. Get access to a file in `servePath`. E. g. type in your browser's address bar: `http://127.0.0.1/dir/index.html` *(Note: The path of `index.html` must be `` `${servePath}/dir/index.html` `` on your local machine).*

5. Turn it off when no more needed:

```js
await staticServer.shutdown()
await staticServer.shutdown(/* callback */)
```
31 changes: 23 additions & 8 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import http from 'http'

import debug from 'debug'

// noinspection JSUnusedGlobalSymbols
/**
* Created at 1398/4/2 (2019/6/23).
* @author {@link https://mirismaili.github.io S. Mahdi Mir-Ismaili}
Expand Down Expand Up @@ -53,18 +54,32 @@ export default class StaticServer {
})
}

listen(): Promise<void> {
// noinspection JSUnusedGlobalSymbols
listen(onListen: () => void = () => {}, onError: (err: Error) => void = () => {}): Promise<void> {
return new Promise((resolve, reject) => {
this.staticServer.on('error', reject)

this.staticServer.listen(this.port, resolve)
}
)
try {
this.staticServer.on('error', err => {
onError(err)
reject(err)
})

this.staticServer.listen(this.port, () => {
onListen()
resolve()
})
} catch (err) {
onError(err)
reject(err)
}
})
}

shutdown(): Promise<void> {
shutdown(callback: (err?: Error) => void = () => {}): Promise<void> {
return new Promise((resolve, reject) =>
this.staticServer.close(err => err === undefined ? resolve() : reject(err))
this.staticServer.close(err => {
callback(err)
err === undefined ? resolve() : reject(err)
})
)
}
}
Expand Down

0 comments on commit b2d82e7

Please sign in to comment.