ローカル端末でNode.jsを実行

Node.js

はじめに

Node.jsアプリケーションをデプロイする前に、ローカル環境でテストを行う必要があります。もちろんそのままNodeアプリケーションを起動、実行することは可能ですが、更に使いやすくするために設定を加えて紹介します。

nodemon をインストール

通常、npm startコマンドでNode.jsアプリケーションを実行した際、コードの修正後にプログラムを停止させnpm startコマンドで再度実行する必要があります。nodemonは、プログラムが修正(更新)されると変更を検出し自動的にアプリケーションを再実行してくれるツールです。

※ 既にインストールしている場合は不要です

PS D:\~ > npm install -g nodemon
PS D:\~ > nodemon -v
2.0.19

Node.jsアプリケーションの作成

PowerShellを開き、任意の場所にNode.jsアプリケーションを作成するディレクトリを作成。

PS D:\~ > mkdir node_sample

作成したディレクトリに移動。

PS D:\~ > cd node_sample
PS D:\~\node_sample >

npm init -yコマンドでNode.jsアプリケーションを初期化。

PS D:\~\node_sample > npm init -y
npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
Wrote to D:\test\package.json:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

プロジェクトディレクトリにpackage.jsonが作成されているので、VSCode等のエディタでpackage.jsonを開く。

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

scriptsプロパティに以下を追記する。

{
 ~ 略 ~
  "scripts": {
     ~ 略 ~
    "start": "node index.js",
    "dev": "nodemon index.js"
  },
   ~ 略 ~
}
プロパティコマンド説明
startnpm run start (yarn start)ローカルサーバを立ち上げます。
devnpm run dev (yarn dev)ローカルサーバを立ち上げ、変更を検出します。

必要なモジュールをインストール。

# NPMの場合
PS D:\~\node_sample > npm install --save express

# Yarn の場合
PS D:\~\node_sample > yarn add express

# 複数のモジュールをインストール
PS D:\~\node_sample > yarn add express dotenv axios dayjs

package.json と同じ階層に index.js ファイルを作成。
以下のコードを記述し、保存する。

'use strict';
require('dotenv').config();
const express = require('express');
const app     = express();

app.get('/', (req, res) => {
  res.status(200).send('OK').end();
});

// Start the server
const PORT = parseInt(process.env.PORT) || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
});

module.exports = app;

PowerShellでアプリケーションを実行。

# NPMの場合
PS D:\~\node_sample > npm run dev

# Yarnの場合
PS D:\~\node_sample > yarn dev

ブラウザを開き、アドレスバーにhttp://localhost:8080/を入力しアクセス。
ポート番号8080は、index.jsの11行目に指定したポート番号になります。
以下の画面が表示されたらOK!

実行中のNode.jsアプリケーションを閉じる場合はCtrl + Cで終了します。

コメント