10
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Node.js】https と fs で、ファイルをダウンロードする

Posted at

環境

$ node -v
v16.2.0
$ yarn info https version
1.0.0
$ yarn info fs version
0.0.1-security
$ yarn info  typescript version
4.3.2

コード

使いやすいようにPromiseを併用しています。
コードは TypeScriptなので、JavaScriptの場合は型定義を消してください。

const download = (uri: string, filename: string) => {
  return new Promise<void>((resolve, reject) =>
    https
      .request(uri, (res) => {
        res
          .pipe(createWriteStream(filename))
          .on("close", resolve)
          .on("error", reject);
      })
      .end()
  );
};

download(
  "https://cdn2.bulbagarden.net/upload/thumb/8/88/006Charizard-Gigantamax.png/600px-006Charizard-Gigantamax.png",
  "Charizard-gmax.png"
).then(() => console.log("done"));

ローカルに Charizard-gmax.png というファイルがダウンロードできているのが確認できます。

600px-006Charizard-Gigantamax.png (600×600)

かんたんな解説

res.pipe は引数に stream.Writable オブジェクト (今回の場合は fs.createWriteStream ) を指定することで、そのオブジェクトにすべてのデータを自動で流し込んでくれます。

参考

10
5
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
10
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?