LoginSignup
2
1

More than 1 year has passed since last update.

https.requestでPromiseを使う

Last updated at Posted at 2021-06-12

https.requesthttp.ClientRequest を返すので、続けて https.on や https.end が利用可能。

環境

$ node -v
v16.2.0
$ yarn info jsdom version
16.6.0
$ yarn info https version
1.0.0
$ yarn info  typescript version
4.3.2

コード

import * as https from "https";

const request = (options) => {
  return new Promise((resolve, reject) => {
    https
      .request(options, (res) => {
        const data = [];
        res.on("data", (d) => data.push(d));
        res.on("end", () => resolve(data.join("")));
      })
      .on("error", reject)
      .end();
  });
};

TypeScript ver.

import * as https from "https";

const request = (options: string | URL | https.RequestOptions) => {
  return new Promise<string>((resolve, reject) => {
    https
      .request(options, (res) => {
        const data = [];
        res.on("data", (d) => data.push(d));
        res.on("end", () => resolve(data.join("")));
      })
      .on("error", reject)
      .end();
  });
};

そのまま jsdom に渡せる。

import { JSDOM } from "jsdom";

request("https://www.google.com/")
  .then((data) => {
    const dom = new JSDOM(data);
    // Google
    console.log(dom.window.document.title);
  });

参考

2
1
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
2
1