かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

Mac OSX High Sierra 開発環境セットアップのメモ (2) node.js

f:id:kikiki-kiki:20180607034038p:plain

CSSプリプロセッサやタスクランナーなどフロントを触るにはnode.jsは必須になっているのでnodeが使える環境のセットアップも必須になってる感じです。

1. nodebrewのインストール

node.jsのバージョン管理をするnodebrewをインストールします。
お好みの方法で、

homebrewでインストール
$ brew install nodebrew
curlでインストール (公式のgithubに書いてある方法)
$ curl -L git.io/nodebrew | perl - setup
nodebrewのパスを通す

1. ~/.bashrc~/.zshrcに下記を記述して保存

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

2. 保存したら下記コマンドを実行してパスを反映する

$ source ~/.bashrc

2. nodebrewでnode.jsをインストール

インストールできるバージョンの確認

$ nodebrew ls-remote

install-binaryコマンドでコンパイル済みのnodeをインストール

# 安定版をインストール
$ nodebrew install-binary stable
# 最新版をインストール
$ nodebrew install-binary latest
# バージョンを指定してインストール
$ nodebrew install-binary <version>

使用するnodeの設定 インストールされているnodeのバージョンを確認

$ nodebrew list
v8.11.2
v10.4.0

current: none

useオプションで使用するnode.jsのバージョンを指定

# 使用するバージョン
$ nodebrew use v8.11.2
# デフォルトで使用するバージョンのエイリアスを作成
$ nodebrew alias default v8.11.2

3. node.jsの確認

別途ターミナルを起動して指定したバージョンになっていることを確認する

$ node -v
v8.11.2

nodebrewのコマンド

参考: GitHub - hokaccha/nodebrew: Node.js version manager

エイリアスの作成・削除
# エイリアスの作成
$ nodebrew alias <key> <version>
# エイリアスの削除
$ nodebrew unalias <key>
インストールしたnode.jsのアンイストール
$ nodebrew uninstall <version>
# Remove source file
$ nodebrew clean <version>
globalにインストールされたNPMパッケージの移行

移行元のバージョンに<version>に指定する。

# Install global NPM packages contained in <version> to current version
$ nodebrew migrate-package <version>
nodebrewのアップデート
$ nodebrew selfupdate

 
nodeの環境を作るのはとても簡単なのでストレスがなくて良いです!
パッケージとかのアップデートは激しいですがw


[参考]

node.js Express でHTMLとか確認できる簡単なローカルサーバー作ってみた

WEBサイトの制作のときならgulpでサーバー起動してCSS・JSを本番と同じようにコンパイルして確認するのが良いのですが、実験や学習用にでわざわざコンパイルまでしなくていいローカル環境が欲しかったのでexpressで作ってみました。

インストール

$ npm install --save express pug

HTMLはpugを使いたかったのでpugもインストールしています

ローカル環境を作る

ファイル構造

package.json
server.js
/root
  |- index.pug
  |- /sample
       |- index.pug
       |- sample.js

/root ディレクトリ内にpugファイルを作りそこで使うJSとかを直接置けるようにしたいと思います。

server.js

'use strict';
const express = require('express'),
      path    = require('path'),
      app     = express();

const rootPath = '/root';

// テンプレートエンジン
app.set('views', path.join(__dirname + rootPath) );
app.set('view engine', 'pug');

// 静的ファイル
app.use(express.static(__dirname + rootPath, { index: false }));

// Routing
app.get('/', (req, res)=> {
  res.render('index');
});

app.get('/:dir', (req, res)=> {
  console.log(req.params.dir);
  res.render(req.params.dir + '/index', {title: req.params.dir});
});

// Error
app.use((err, req, res, next)=> {
  console.log('>> ERROR >>', err);
  res.status(err.status || 500);
  res.send(err.message);
});

app.listen(3000, ()=> {
  console.log("Express Server\nopen: http://localhost:3000");
});

ローカルサーバーの起動

$ node server.js

簡単なサーバーはこれで機能するようになりました。

TODO
  • 初回に自動的にブラウザを開く
  • ファイルを変更したら自動的にブラウザをリロードする

[参考]

自転車えくすぷれす

自転車えくすぷれす

Gulp 4 gulp.seriesとgulp.parallel

gulp v4 で追加されたgulp.seriesgulp.parallelを試してみた

  • gulp.series(...tasks) ... 順番に実行する
  • gulp.parallel(...tasks) ... 並列に実行をする

GitHubのサンプル

gulp.task('one', function(done) {
  // do stuff
  done();
});

gulp.task('two', function(done) {
  // do stuff
  done();
});

gulp.task('default', gulp.series('one', 'two', function(done) {
  // do more stuff
  done();
}));

呼び出されるタスク(関数)の引数にdoneがあり、タスクの最後で実行されています。

fn
The fn is passed a single argument, callback, which is a function that must be called when work in the fn is complete. Instead of calling the callback function, async completion can be signalled by:

  • Returning a Stream or EventEmitter
  • Returning a Child Process
  • Returning a Promise
  • Returning an Observable

Once async completion is signalled, if another run is queued, it will be executed.
出典: gulp/API.md at master · gulpjs/gulp · GitHub

これはタスクの完了を通知するコールバック関数で、タスクランナーでよくあるreturn gulp.src()...をしない場合はdone()の実行を忘れると次のようなタスクの終了がわからないというエラーが表示されます。

[00:00:00] The following tasks did not complete: mytask
[00:00:00] Did you forget to signal async completion?

gulp.series()で実行されるタスクは、この終了の合図があると次のタスクに進むので、gulp.series()内にgulp.parallel()があると並行処理されるタスク全てが完了するまで待機されます。

サンプル

"use strict";
const gulp = require('gulp');

// TASK
function task1(done) {
  console.log('task 1');
  setTimeout(function() {
    console.log('task 1 >> 1100ms');
    done();
  }, 1100);
}

function task2(done) {
  console.log('task 2');
  setTimeout(function() {
    console.log('task 2 >> 1000ms');
    done();
  }, 1000);
}

function task3(done) {
  console.log('task 3');
  done();
}

// Default
gulp.task('default', gulp.series(
  gulp.parallel(task1, task2),
  task3,
  function(done) {
    console.log('default');
    done();
  }
));

👇 実行結果

$ npx gulp
[00:10:20] Using gulpfile ~/example/gulpfile.js
[00:10:20] Starting 'default'...
[00:10:20] Starting 'task1'...
[00:10:20] Starting 'task2'...
task 1
task 2
task 2 >> 1000ms
[00:10:21] Finished 'task2' after 1 s
task 1 >> 1100ms
[00:10:21] Finished 'task1' after 1.1 s
[00:10:21] Starting 'task3'...
task 3
[00:10:21] Finished 'task3' after 305 μs
[00:10:21] Starting '<anonymous>'...
default
[00:10:21] Finished '<anonymous>' after 278 μs
[00:10:21] Finished 'default' after 1.11 s

このように、gulp.seriesで順番を指定するとタスク内にsetTimeoutのような処理があってもdoneが実行されるまで、次の処理は実行されません。

以前はrun-sequenceなどを使って順番を決めていましたが、gulp v4からはgulp.seriesgulp.parallelを使えば少しタイプ数は増えますが複雑なタスクの管理がgulpだけでできそうです!


[参考]