Node.js 環境構築(2020年5月時点)とJavaScriptの実行
はじめに
本業は上流SE、副業でRailsエンジニアをやっているのだけれど、本業で急遽フロントエンド(しかもSPA)を書くことになった。
JSは雰囲気で触れるぐらいなので慌ててJSを勉強し直すことに。
とりあえず実行環境としてNode.jsを手元のMacBookに構築する。
構築環境
導入環境はMacBook Pro 13.3インチ(2020)と
OSはCatalina10.15.5で確認しています。
Homebrewは導入済みの前提。
MacOS Catalinaからは標準shellがzshになっているので気をつける。
nodebrewのインストール
nodebrewで実行環境を管理する。 github.com
pyenv,rbenvのようにnodejsのバージョンを管理することができる。
Homebrewでインストールする。
$ brew install nodebrew
完了後は以下のコマンドでバージョンを確認する。
$ nodebrew nodebrew 1.0.1 Usage: nodebrew help Show this message nodebrew install <version> Download and install <version> (from binary) nodebrew compile <version> Download and install <version> (from source) nodebrew install-binary <version> Alias of `install` (For backword compatibility) nodebrew uninstall <version> Uninstall <version> nodebrew use <version> Use <version> nodebrew list List installed versions nodebrew ls Alias for `list` nodebrew ls-remote List remote versions nodebrew ls-all List remote and installed versions nodebrew alias <key> <value> Set alias nodebrew unalias <key> Remove alias nodebrew clean <version> | all Remove source file nodebrew selfupdate Update nodebrew nodebrew migrate-package <version> Install global NPM packages contained in <version> to current version nodebrew exec <version> -- <command> Execute <command> using specified <version> Example: # install nodebrew install v8.9.4 # use a specific version number nodebrew use v8.9.4
node.jsのインストール
以下のコマンドでnodesjの安定版をインストールする。
$ nodebrew install stable
すると、以下のエラーが出た。
Fetching: https://nodejs.org/dist/v14.3.0/node-v14.3.0-darwin-x64.tar.gz Warning: Failed to create the file Warning: /Users/xxxxxx/.nodebrew/src/v14.3.0/node-v14.3.0-darwin-x64.tar.gz: Warning: No such file or directory curl: (23) Failed writing body (0 != 979) download failed: https://nodejs.org/dist/v14.3.0/node-v14.3.0-darwin-x64.tar.gz
ディレクトリが無いので作成する。
mkdir -p ~/.nodebrew/src
再トライすると無事インストールされた。
$ nodebrew install stable Fetching: https://nodejs.org/dist/v14.3.0/node-v14.3.0-darwin-x64.tar.gz ################################################################# 100.0% Installed successfully
インストールの確認をする。
$ nodebrew ls v14.3.0 current: none
currentに指定するにはuseを使う。
$ nodebrew use v14.3.0 use v14.3.0 $ nodebrew ls v14.3.0 current: v14.3.0
これだけだとパスが通っていないため、パスを通す。 zshの場合は.zprofileか.zshrcのどちらか。
$ echo 'export PATH=$HOME/.nodebrew/current/bin:$PATH' >> ~/.zprofile $ source ~/.zprofile $ node -v v14.3.0
これでnode.jsの環境構築はOK。
jsの実行
以下のコマンドで、pythonの対話モードのようにjsを実行できる。
$ node
この環境を使ってJavaScriptのおさらいをした。
当然だけどhtml等に関連するコマンドは実行できないので、そこだけ気をつける。