LoginSignup
4
3

More than 5 years have passed since last update.

[Node.js]WebページのHTMLをダウンロードする方法

Last updated at Posted at 2018-02-27

WebページのHTMLをダウンロードする方法

index.js
//モジュールのインポート
const https = require('https');
const fs = require('fs');

// ダウンロード先のURL
const url = 'https://github.com/';
// HTMLの保存先
const savepath = 'test.html';

https.get(url, (res) => {
  res.pipe(fs.createWriteStream(savepath))
  .on('error', (error) => console.error(error))
  .on('finish', () => console.log('ok'));
});

解説:
1. モジュールのインポート
インポートするモジュールはアクセスするページのプロトコルによって異なります。
"http://"にアクセスするならhttpモジュールをインポートしてください。
2. Webページにgetメソッドでアクセスする
https.getに与える引数は、URL,コールバック関数です。

スクリプトの実行

node ./index.js を実行すると、プロジェクトのディレクトリの直下にtest.htmlが出力されます。

おまけ

index.js
//モジュールのインポート
import fs from 'fs'
import request from 'request'

// ダウンロード先のURLを指定
var url = "https://github.com/";
// HTMLの保存先を指定
var savepath = "test.html";
var outfile = fs.createWriteStream(savepath);

request(url).pipe(outfile)

これでも同じことができます。

4
3
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
4
3