LoginSignup
3
5

More than 5 years have passed since last update.

Mac Node.jsインストール〜ローカルサーバー起動

Last updated at Posted at 2016-10-05

環境

  • MacBook Air El Capitan iOS 10.11.6

やること

  • MacにNode.jsインストール
  • ローカルサーバー起動
  • チャットアプリ作成

環境構築 ケース1:公式よりpkgインストール

  • パッケージ管理とか面倒臭い!とにかく手っ取り早く始めたい向け

インストール

  • 以下いずれかの公式サイトより「Install」

  • ダウンロードした「node-v0.11.11.pkg」を選択し、ウィザードに従いインストール

  • 私の環境では以下になりました
    nodejs-setupcomplete.png

環境構築 ケース2:バージョンマネージャーを利用してインストール

  • いやいや、俺はちゃんとパッケージ管理したいんだ!という方向け

nodebrewインストール

Yosemite以降は不可のようです(2016/10/05執筆時点)

  • Homebrewを使い、nodebrewを入れます
$ brew install nodebrew

Yosemite以降の方

  • 上記のようにHomebrew経由でnodebrewを入れた場合、nodebrew install-binaryにて以下のエラーになりました
$ nodebrew install-binary v0.11.11
Fetching: https://nodejs.org/dist/v0.11.11/node-v0.11.11-darwin-x64.tar.gz
Warning: Failed to create the file 
Warning: /Users/shockyeah/.nodebrew/src/v0.11.11/node-v0.11.11-darwin-x64.tar.g
Warning: z: No such file or directory

curl: (23) Failed writing body (0 != 942)
download failed: https://nodejs.org/dist/v0.11.11/node-v0.11.11-darwin-x64.tar.gz
$ curl -L git.io/nodebrew | perl - setup

共通

  • 起動時に読み込みされるようPATHの設定、読み込み
$ echo 'export PATH=$HOME/.nodebrew/current/bin:$PATH' >> ~/.bashrc
$ source ~/.bashrc

Node.jsインストール

  • インストール可能なバージョン一覧を表示
$ nodebrew ls-remote
  • インストール
$ nodebrew install-binary v0.11.11
  • 対象バージョンを有効化
$ nodebrew use v0.11.11
use v0.11.11
  • インストール済みバージョンを確認
$ nodebrew ls
v0.11.11

current: v0.11.11

動作確認

  • バージョン
$ node -v
v0.11.11

ローカル上にサーバーを立ててHello World

  • 以下を任意のディレクトリへ作成
example.js
var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');
  • 実行
$ node example.js 
  • 任意のブラウザで以下にアクセス

  • 「Hello World」が表示されればOK

チャットアプリを作ってみる

  • この時点まででNode.jsのパッケージを管理するnpmコマンドが利用出来るようになっています。
    これを利用してsocket.ioをインストール。
$ npm install socket.io

参考

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