LoginSignup
10
15

More than 5 years have passed since last update.

node.jsのExpressを使ってローカルサーバを構築する。

Posted at

はじめに

node.jsのExpressを使った方法でローカルサーバを構築し、gulpから実行してみた。
その備忘録として書いておきます。

GitHubにアップしています。
ExpressServer

前提

node.jsがインストール済みであり、npmの使い方もある程度わかっているものとします。

Expressのインストール

適当なフォルダを作成しターミナルで移動後、package.jsonを生成します。

ターミナル
$ npm ini

続いて、Expressのインストールしましょう。
ターミナルから以下のコマンドを実行します。

ターミナル
$ npm install express --save-dev

サーバ構築

今回は、以下のようなディレクトリでサーバを作成します。

ディレクトリ
Root
  server.js
  dest
    index.html
  gulpfile.js
  package.json

server.jsの内容

Expressの設定と、ポートの設定くらいの簡素な内容となっています。

server.js
let express = require('express');

let app = express();
app.use(express.static('dest'));

let port = 3000;
app.listen(port, ()=> {
  console.log('Expressサーバー起動');
});

サーバー起動

以下のコマンドでサーバを起動します。

ターミナル
$ node server.js

正常に起動されればコマンドラインに「Expressサーバー起動」と表示されます。
ブラウザからhttp://localhost:3000 にアクセスするとindex.htmlの内容が表示されます。

gulpからサーバ起動する

gulp-execを使うと、gulpからシェルスクリプトを実行できるようになります。

ターミナル
$ npm install gulp-exec --save-dev

gulpfile.jsに以下のようにserver.jsを実行する記述をします。

gulpfile.js
gulp.task('exec', function() {
    gulp.src('./') .pipe(exec('node server.js'));
});

ターミナルから実行してみましょう。

ターミナル
$ gulp exec

再び、ブラウザからhttp://localhost:3000 にアクセスするとindex.htmlの内容が表示されるはず、、、です。

以上、簡単ですがnode.jsのexpressを使ったローカルサーバ構築手順でした。
catch you later.

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