機械系大学生の修行ログ

sh-lu0's Tech Blog

アイドルが力をくれる

Node.jsの環境構築・HelloWorld (Mac)

Homebrewインストール

macOS 用パッケージマネージャー — macOS 用パッケージマネージャー
インストールする

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

パスワードを求められるのでmacのパスワードを入力 ※Xcodeがインストールされている必要がある

バージョン確認

$ brew --version
Homebrew 1.8.4
Homebrew/homebrew-core (git revision 9d67f4; last commit 2018-12-06)

Nodebrewインストール

インストール

$ brew install nodebrew

バージョン確認

$ npm view node version
11.3.0

Node.jsインストール

最新バージョンをインストール

$ nodebrew install-binary latest

エラーがでた

Fetching: https://nodejs.org/dist/v11.3.0/node-v11.3.0-darwin-x64.tar.gz
Warning: Failed to create the file
Warning: /Users/hoge/.nodebrew/src/v11.3.0/node-v11.3.0-darwin-x64.tar.gz:
Warning: No such file or directory
                                                                           0.0%
curl: (23) Failed writing body (0 != 847)
download failed: https://nodejs.org/dist/v11.3.0/node-v11.3.0-darwin-x64.tar.gz

ディレクトリ作成

$ mkdir -p ~/.nodebrew/src

出来た

$ nodebrew install-binary latest  
Fetching: https://nodejs.org/dist/v11.3.0/node-v11.3.0-darwin-x64.tar.gz
######################################################################## 100.0%
Installed successfully

バージョン確認

$ node --version
v10.14.1

npmでプロジェクト作成

$ mkdir project_name
$ cd project_name
$ npm init //npmでプロジェクトを開始する

package.jsonが作成される

{
  "name": "project_name",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "sh-lu0",
  "license": "ISC",
    "description": "",
}

$ npm install ライブラリ名 --saveでライブラリをインストールすると,自動でpackage.jsonにインストールしたモジュールとバージョンが記録される.

Node.jsでWebサーバーを立てる

先ほど作ったプロジェクトの中にhello-server.jsを作成

// httpモジュール読み込み
const http = require('http')

// webサーバーを実行
const svr = http.createServer(handler) //Webサーバー生成
svr.listen(8081) //クライアント(ポート8081)で待ち受け開始

//サーバーにアクセスされたとき
function handler(req, res) {
  console.log('url:', req.url)
  console.log('method;', req.method)
  //HTTPヘッダーを出力
  res.writeHead(200, {
    'Content-Type': 'text/html'
  })
  //レスポンスの本体を出力
  res.end('<h1>Hello,World</h1>\n')
}

ターミナルで

$ node hello-server.js

Webブラウザhttp://localhost:8081にアクセス
f:id:sh_lu0:20181209012042p:plain
やったね!



参考にしたサイト
MacにNode.jsをインストール - Qiita
ありがとうございます