3
1

More than 3 years have passed since last update.

node.jsをインストールしてurl指定のファイルをダウンロードする

Posted at

前提条件

 CentOS6.5
 node.js v0.12.4 ← これをインストールする

手順

  1. node.jsのインストール
  2. sudoコマンド実行時のパスを普段のユーザのパスと同等にしてやる
  3. プログラム作成
  4. 実行

1.node.jsのインストール

CentOSにsshログインして以下のコマンド実行。
実は一度インストールした後にコマンドの再確認的な意味合いでやったので
already installedとか出てるけど、そこは気にしないことにする

[vagrant@localhost ~]$ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.25.3/install.sh | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  7149  100  7149    0     0  10538      0 --:--:-- --:--:-- --:--:-- 25084
=> Downloading nvm from git to '/home/vagrant/.nvm'
=> fatal: destination path '/home/vagrant/.nvm' already exists and is not an empty directory.
[vagrant@localhost ~]$ nvm install v0.12.4
v0.12.4 is already installed.
Now using node v0.12.4 (npm v2.10.1)
[vagrant@localhost ~]$ nvm alias default v0.12.4
default -> v0.12.4
[vagrant@localhost ~]$ node -v
v0.12.4
[vagrant@localhost ~]$

2. sudoコマンド実行時のパスを普段のユーザのパスと同等にしてやる

nvmを利用してNode.jsをインストールした場合、sudoコマンドを利用した時に
npmやnodeコマンドが利用できないためvisudoを使って利用できるようにする

$sudo visudo

テキストファイルの編集画面に切り替わるので以下のように編集する

Defaults env_reset
↓↓
Defaults !env_reset

# Defaults env_keep += "HOME"
↓↓
Defaults env_keep += "HOME"

Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin
↓↓
# Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin

3. プログラム作成

以下のプログラムを作成する。ミニサイズなので全文おいとく。
拡張子は"js"

/home/vagrant/src/ch02/01-download/download-node.js
// urlにあるファイルを savepath にダウンロードする

// ダウンロード元URLの指定
var url = "http://kujirahand.com"

//保存先のパスを指定
var savepath = "test.html"

// 利用モジュールの取り込み
var http = require('http'); // HTTPのモジュール
var fs = require('fs');     // ファイル関連モジュール

// 出力先を指定
var outfile = fs.createWriteStream(savepath);

// 非同期でURLからファイルをダウンロード
http.get(url, function(res) {
    res.pipe(outfile);
    res.on('end', function (){
        outfile.close();
        console.log("ok");
    });
});

4.実行する

jsのファイルのある場所まで移動してnodeコマンド実行。
プログラムのつくりの問題だけど"ok"の出力があれば無事成功。

[vagrant@localhost 01-download]$ pwd
/home/vagrant/src/ch02/01-download
[vagrant@localhost 01-download]$ node download-node.js
ok

結果確認

同フォルダにtest.htmlができているので内容チェックして確認

[vagrant@localhost 01-download]$ ls
download-node.js  test.html
[vagrant@localhost 01-download]$ cat test.html
<html><body><a href="https://kujirahand.com/wiki/index.php">kujirahand.com</a><br></body></html>[vagrant@localhost 01-download]$

おわりに

インストールしてしまえば結構さらっと終わった
javascriptでこんなに作りこんだことないから
ちょっと慌てるけど徐々に慣れていけばいいかなと。

~おしまい~

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