LoginSignup
1
0

More than 3 years have passed since last update.

Node.js: http.IncommingMessageをHTTP形式の文字列に変換する関数

Posted at

Node.jsのhttp.IncommingMessageをHTTP形式の文字列に変換するデバッグ用関数を作ったので紹介します。

どんな関数かというと、次のように第一引数にhttp.IncommingMessageオブジェクトを渡すと:

textifyRequest(req)

下記のような文字列をPromiseで返す関数です:

POST /foobar HTTP/1.1
Host: localhost:9000
Connection: close
Transfer-Encoding: chunked

hello

http.IncommingMessageをHTTP形式の文字列に変換する関数

const textifyRequest = (req: IncomingMessage): Promise<string> =>
  new Promise(resolve => {
    let text = `${req.method} ${req.url} HTTP/${req.httpVersion}\n`

    // serialize headers
    let nextKey = undefined as string | undefined
    for (let keyOrValue of req.rawHeaders) {
      if (nextKey === undefined) {
        nextKey = keyOrValue
      } else {
        text += `${nextKey}: ${keyOrValue}\n`
        nextKey = undefined
      }
    }
    text += '\n'

    // serialize body
    req
      .on('data', chunk => text += chunk)
      .on('readable', () => req.read())
      .on('end', () => resolve(text))
  })

使用例

// HTTPサーバ
http.createServer((req: IncomingMessage, res: ServerResponse): void => {
  textifyRequest(req).then(console.log) // リクエストを受け取ったところに仕込む
  res.end()
}).listen(9000, () => {
  // 上で立てたHTTPサーバにリクエストを送ってみる
  const req = http.request({ host: 'localhost', port: 9000, method: 'POST', path: '/foobar' })
  req.write('hello')
  req.end()
})

実行結果

POST /foobar HTTP/1.1
Host: localhost:9000
Connection: close
Transfer-Encoding: chunked

hello

注意点

HTTPボディを文字列バッファに積んで返すので、データサイズの大きいリクエストには不向きな実装になっています。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0