LoginSignup
37

More than 5 years have passed since last update.

5分で作るNode.js開発環境

Last updated at Posted at 2014-08-11

開発環境

vagantでCentOS ver6.5に開発環境をセットアップします。

vagrantのセットアップ

bash
$ vagrant box add centos65 https://github.com/2creatives/vagrant-centos/releases/download/v6.5.3/centos65-x86_64-20140116.box
$ mkdir nodejs
$ cd nodejs
$ vagrant init
$ vagrant up
$ vagrant ssh

これでひとまずCentOS6.5の環境が出来ました。
あとはCentOS上にログインしてyum upgradeとかvimとかopensslとかインストールしておきましょう。

NodeJSインストール

NodeJSとjshintをインストール jshintはJSの構文チェッカーなので必須ではないです。

bash
$ sudo rpm -ivh http://ftp.riken.jp/Linux/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
$ sudo yum install nodejs npm --enablerepo=epel
$ sudo npm install -g jshint

HelloWorld

毎度おなじみHelloWorldを出力します。
まずどこでも良いので、HelloWorld.jsを作成します。

HelloWorld.js
// HTTPパッケージを読み込み
var http = require('http');

// WebServerObjectを作成 
var server = http.createServer();
// HTTP RequestがあったらdoRequestで処理
server.on('request', doRequest);
// リクエストを受け取るポートを指定
server.listen(1234);
console.log('Server running!');

// リクエストの処理
function doRequest(req, res) {
    // ヘッダー
    res.writeHead(200, {'Content-Type': 'text/plain'});
    // 出力
    res.write('Hello World\n');
    // 終了
    res.end();
}

さて準備が整ったので、いざ動かしてみましょう。

bash
$ node HelloWorld.js

これでブラウザでvagrant上の「ipアドレス:1234」にアクセスすればHelloWorldが表示されます。

以上!

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
37