LoginSignup
19
15

More than 5 years have passed since last update.

MACにnode.jsをインストールしてHello World

Posted at

Macにnode.jsをインストールして、"Hello World"を表示するまでの手順です。
node.jsにはnodebrewを使います。

nodebrewはnode.jsの複数のnode.jsのバージョン管理し切り替えを可能にするツールです

補足:homebrewのインストールしてあるのが前提です

nodebrewをインストール

インストール

$ brew install nodebrew

バージョン確認

$ nodebrew -v
nodebrew 0.9.2
...

以下のコマンドでインストール可能なバージョンの一覧が表示できます。

node.jsインストール

インストール可能なバージョンの確認

$ nodebrew ls-remote

最新版をインストール

$ nodebrew install-binary latest

installでもOKだけど、install-binaryだとコンパイル済みのバイナリがインストールされてビルドの時間がかからない。

エラーが出た

上記を実施したが下記エラーが出た

$ nodebrew install-binary latest
fetch: http://nodejs.org/dist/v6.9.1/node-v6.9.1-darwin-x64.tar.gz
Warning: Failed to create the file
Warning: /Users/sonoda/.nodebrew/src/v6.9.1/node-v6.9.1-darwin-x64.tar.gz: No
Warning: such file or directory

Warningがでておこられた、ディレクトリがないようなので、ディレクトリ作った

mkdir ~/.nodebrew
mkdir ~/.nodebrew/src

再度実施すると無事インストールできました

インストールされているNodeのバージョンの確認

$ nodebrew list
v6.9.1

バージョンを指定

nodebrew use  v6.9.1

パスを通す

~/.bash_profile にパスを追記.bash_profileがなければ作成

.bash_profile
export PATH=$HOME/.nodebrew/current/bin:$PATH

別のコンソールを立ち上げ、パスが通っているかとVersion確認
shell-session:.bash_profile
$ node -v
v6.9.1

node.jsでHello world

http://nodejs.jp/nodejs.org_ja/
に書いてあるとおりなんですが

example.jsを作成して

example.js
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

実行して

$ node example.js
Server running at http://127.0.0.1:1337/

ブラウザで

http://localhost:1337/

にアクセスしてHello Worldが出れば成功

19
15
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
19
15