Created
April 22, 2019 03:18
-
-
Save swashcap/545ea386e1f453ac4a1f4ad610ef603b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const assert = require("assert"); | |
const hapi = require("hapi"); | |
const http = require("http"); | |
const getRootHandler = response => ({ | |
handler() { | |
return response; | |
}, | |
method: "GET", | |
path: "/" | |
}); | |
const listener = http.createServer(); | |
const port = 3000; | |
const request = () => | |
new Promise((resolve, reject) => { | |
const req = http.request( | |
{ | |
hostname: "0.0.0.0", | |
port, | |
method: "GET", | |
path: "/" | |
}, | |
res => { | |
let body = ""; | |
res.setEncoding("utf8"); | |
res.on("data", chunk => { | |
body += chunk; | |
}); | |
res.on("end", () => | |
resolve({ | |
body, | |
headers: res.headers, | |
statusCode: res.statusCode | |
}) | |
); | |
} | |
); | |
req.on("error", reject); | |
req.end(); | |
}); | |
const main = async () => { | |
// Create a server | |
const server1 = hapi.Server({ | |
autoListen: false, | |
listener | |
}); | |
// Register a `/` route that responds with "Server 1" | |
server1.route(getRootHandler("Server 1")); | |
// Start the `hapi.Server` and `http.Server` | |
await Promise.all([ | |
server1.start(), | |
new Promise(resolve => listener.listen(port, resolve)) | |
]); | |
// Check server1's response | |
const { body: body1, statusCode: statusCode1 } = await request(); | |
assert.equal(statusCode1, 200); | |
assert.equal(body1, "Server 1"); | |
console.log("server1 response good") | |
// Stop the server. This also appears to stop `listener` | |
await server1.stop(); | |
// Create a new server and set its listener to the same `http.Server` | |
const server2 = hapi.Server({ | |
autoListen: false, | |
listener | |
}); | |
// Register a `/` route that responds with "Server 2" | |
server2.route(getRootHandler("Server 2")); | |
// Start everything | |
await Promise.all([ | |
server2.start(), | |
new Promise(resolve => listener.listen(port, resolve)) | |
]) | |
// Check server2's response | |
const { body: body2, statusCode: statusCode2 } = await request(); | |
assert.equal(statusCode2, 200); | |
assert.equal(body2, "Server 2"); | |
console.log("server2 response good") | |
await server2.stop(); | |
}; | |
main() | |
.then(() => console.log("All good!")) | |
.catch(error => { | |
console.error(error); | |
process.exit(1); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Seeing this throw along with an unhandled rejection: