Skip to content

Commit

Permalink
HttpServer ready promise
Browse files Browse the repository at this point in the history
  • Loading branch information
richytong committed Nov 18, 2024
1 parent 20e5733 commit df3b659
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
13 changes: 12 additions & 1 deletion HttpServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,18 @@ const StringStream = require('./StringStream')
* ```
*/
const HttpServer = function (httpHandler) {
return http.createServer(httpHandler)
const server = http.createServer(httpHandler)

server.ready = new Promise(resolve => {
server._listeningResolve = resolve
})
const originalListen = server.listen
server.listen = (...args) => {
server._listeningResolve()
return originalListen.apply(server, args)
}

return server
}

module.exports = HttpServer
15 changes: 8 additions & 7 deletions HttpServer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ const test = Test('HttpServer', HttpServer)
response.write('hello')
response.end()
}, async server => {
await new Promise(resolve => {
server.listen(3001, async () => {
const response0 = await fetch('http://localhost:3001')
assert.strictEqual(await response0.text(), 'hello')
assert.strictEqual(response0.headers.get('content-type'), 'text/plain')
server.close(resolve)
})
server.listen(3001, async () => {
console.log('Test server listening on port 3001')
})
await server.ready

const response0 = await fetch('http://localhost:3001')
assert.strictEqual(await response0.text(), 'hello')
assert.strictEqual(response0.headers.get('content-type'), 'text/plain')
server.close()
})

if (process.argv[1] == __filename) {
Expand Down

0 comments on commit df3b659

Please sign in to comment.