/
hello-world.js
48 lines (36 loc) · 1.09 KB
/
hello-world.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const http = require('node:http')
const got = require('got')
const intercept = require('../index.js')
/**
* Return a 200 response with a "Hello, world!" response body
* for any request
*
* @param {any} options
* @param {http.ClientRequest} request
*/
function onIntercept(options, request) {
const response = new http.IncomingMessage(request.socket)
// (1) set response header data
response.statusCode = 200
response.rawHeaders = []
response.headers = {}
// @ts-expect-error - no idea why `.req` is not typed on ClientRequest
request.res = response
// @ts-expect-error - no idea why `.res` is not typed on IncomingMessage
response.req = request
request.emit('response', response)
// (2) set response body data
response.push('Hello, world!')
// (3) finish the response
response.complete = true
response.push(null)
}
run()
async function run() {
const reset = intercept(onIntercept)
console.log('Intercepted:')
console.log(await got('https://example.com').text())
console.log('\n\nNot Intercepted:')
reset()
console.log(await got('https://example.com').text())
}