JavaScript: Node.jsでWebアプリケーションを作る最初の一歩

JavaScript
Nodeあめ

npmbrewからnodeをインストールした後のMacで、何も無いフォルダに環境を作ってサーバーを起動し、”Hello World”とブラウザに表示させる迄の整理。

JavaScriptの準備

まずはJavaScriptを使う為の準備から。

Webアプリを作りたいフォルダ(今回は”myapp”)に移動、npm initを実行する。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
% cd myapp
% npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (myapp)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/~/myapp/package.json:
{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)
npm notice
npm notice New patch version of npm available! 8.1.0 -> 8.1.4
npm notice Changelog: https://github.com/npm/cli/releases/tag/v8.1.4
npm notice Run npm install -g npm@8.1.4 to update!
npm notice
% cd myapp % npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help init` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (myapp) version: (1.0.0) description: entry point: (index.js) test command: git repository: keywords: author: license: (ISC) About to write to /Users/~/myapp/package.json: { "name": "myapp", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } Is this OK? (yes) npm notice npm notice New patch version of npm available! 8.1.0 -> 8.1.4 npm notice Changelog: https://github.com/npm/cli/releases/tag/v8.1.4 npm notice Run npm install -g npm@8.1.4 to update! npm notice
% cd myapp
% npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (myapp) 
version: (1.0.0) 
description: 
entry point: (index.js) 
test command: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /Users/~/myapp/package.json:
{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
Is this OK? (yes) 
npm notice 
npm notice New patch version of npm available! 8.1.0 -> 8.1.4
npm notice Changelog: https://github.com/npm/cli/releases/tag/v8.1.4
npm notice Run npm install -g npm@8.1.4 to update!
npm notice 

npm initの入力後、
いくつか質問を聞かれるが全てリターンキーで進めて構わない。

フォルダには”package.json”が出来る。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
% ls
package.json
% ls package.json
% ls          
package.json

中身は以下の通り。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
% cat package.json
{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
% cat package.json { "name": "myapp", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" }
% cat package.json 
{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Expressの導入

続いて、複雑なWebアプリを効率よく開発できるように便利な機能(パッケージ化されたモジュール)が統合されたフレームワーク、expressをインストールする為に、”npm install express”と入力。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
% npm install express
added 50 packages, and audited 51 packages in 3s
found 0 vulnerabilities
% npm install express added 50 packages, and audited 51 packages in 3s found 0 vulnerabilities
% npm install express
added 50 packages, and audited 51 packages in 3s
found 0 vulnerabilities

完了したので、フォルダの中身を見る。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
% ls
node_modules package-lock.json package.json
% ls node_modules package-lock.json package.json
% ls
node_modules      package-lock.json package.json

“node_modules”(フォルダ)と”package-lock.json”と言うファイルが出来ている。

以下はpackage.jsonの中身。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cat package.json
{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
cat package.json { "name": "myapp", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "express": "^4.17.1" } }
cat package.json 
{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}

見ると、12行目以降に
“dependencies”: { “express”: “^4.17.1” }
と言う記述が増えているのが分かる。

ついでにフォルダnode_modulesの中身を見てみる。
treeコマンドで1階層下だけ表示。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
% tree -L 1
.
├── accepts
├── array-flatten
├── body-parser
├── bytes
├── content-disposition
├── content-type
├── cookie
├── cookie-signature
├── debug
├── depd
├── destroy
├── ee-first
├── encodeurl
├── escape-html
├── etag
├── express
├── finalhandler
├── forwarded
├── fresh
├── http-errors
├── iconv-lite
├── inherits
├── ipaddr.js
├── media-typer
├── merge-descriptors
├── methods
├── mime
├── mime-db
├── mime-types
├── ms
├── negotiator
├── on-finished
├── parseurl
├── path-to-regexp
├── proxy-addr
├── qs
├── range-parser
├── raw-body
├── safe-buffer
├── safer-buffer
├── send
├── serve-static
├── setprototypeof
├── statuses
├── toidentifier
├── type-is
├── unpipe
├── utils-merge
└── vary
49 directories, 0 files
% tree -L 1 . ├── accepts ├── array-flatten ├── body-parser ├── bytes ├── content-disposition ├── content-type ├── cookie ├── cookie-signature ├── debug ├── depd ├── destroy ├── ee-first ├── encodeurl ├── escape-html ├── etag ├── express ├── finalhandler ├── forwarded ├── fresh ├── http-errors ├── iconv-lite ├── inherits ├── ipaddr.js ├── media-typer ├── merge-descriptors ├── methods ├── mime ├── mime-db ├── mime-types ├── ms ├── negotiator ├── on-finished ├── parseurl ├── path-to-regexp ├── proxy-addr ├── qs ├── range-parser ├── raw-body ├── safe-buffer ├── safer-buffer ├── send ├── serve-static ├── setprototypeof ├── statuses ├── toidentifier ├── type-is ├── unpipe ├── utils-merge └── vary 49 directories, 0 files
% tree -L 1
.
├── accepts
├── array-flatten
├── body-parser
├── bytes
├── content-disposition
├── content-type
├── cookie
├── cookie-signature
├── debug
├── depd
├── destroy
├── ee-first
├── encodeurl
├── escape-html
├── etag
├── express
├── finalhandler
├── forwarded
├── fresh
├── http-errors
├── iconv-lite
├── inherits
├── ipaddr.js
├── media-typer
├── merge-descriptors
├── methods
├── mime
├── mime-db
├── mime-types
├── ms
├── negotiator
├── on-finished
├── parseurl
├── path-to-regexp
├── proxy-addr
├── qs
├── range-parser
├── raw-body
├── safe-buffer
├── safer-buffer
├── send
├── serve-static
├── setprototypeof
├── statuses
├── toidentifier
├── type-is
├── unpipe
├── utils-merge
└── vary
49 directories, 0 files

これが全部パッケージという理解。

下記は最初の3つのフォルダ(パッケージ)だけ深掘り。他のフォルダもこんな感じでフォルダ、ファイルが入っている。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
.
├── accepts
│ ├── HISTORY.md
│ ├── LICENSE
│ ├── README.md
│ ├── index.js
│ └── package.json
├── array-flatten
│ ├── LICENSE
│ ├── README.md
│ ├── array-flatten.js
│ └── package.json
├── body-parser
│ ├── HISTORY.md
│ ├── LICENSE
│ ├── README.md
│ ├── index.js
│ ├── lib
│ │ ├── read.js
│ │ └── types
│ │ ├── json.js
│ │ ├── raw.js
│ │ ├── text.js
│ │ └── urlencoded.js
│ └── package.json
. ├── accepts │ ├── HISTORY.md │ ├── LICENSE │ ├── README.md │ ├── index.js │ └── package.json ├── array-flatten │ ├── LICENSE │ ├── README.md │ ├── array-flatten.js │ └── package.json ├── body-parser │ ├── HISTORY.md │ ├── LICENSE │ ├── README.md │ ├── index.js │ ├── lib │ │ ├── read.js │ │ └── types │ │ ├── json.js │ │ ├── raw.js │ │ ├── text.js │ │ └── urlencoded.js │ └── package.json
.
├── accepts
│   ├── HISTORY.md
│   ├── LICENSE
│   ├── README.md
│   ├── index.js
│   └── package.json
├── array-flatten
│   ├── LICENSE
│   ├── README.md
│   ├── array-flatten.js
│   └── package.json
├── body-parser
│   ├── HISTORY.md
│   ├── LICENSE
│   ├── README.md
│   ├── index.js
│   ├── lib
│   │   ├── read.js
│   │   └── types
│   │       ├── json.js
│   │       ├── raw.js
│   │       ├── text.js
│   │       └── urlencoded.js
│   └── package.json

サーバーの起動:app.jsの作成

続いて、サーバーを起動させてブラウザに文字を表示させる。

下記の通り記載したファイルapp.jsを作成。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
% cat app.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.render('hello.ejs');
});
app.listen(3000);
% cat app.js const express = require('express'); const app = express(); app.get('/', (req, res) => { res.render('hello.ejs'); }); app.listen(3000);
% cat app.js 
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.render('hello.ejs');
  });
  
app.listen(3000);

ファイルapp.jsの最初の1行(2行目)でexpressを読み込んで、
次の1行(3行目)でappにexpressを代入してexpressを使う準備。

flaskでいうところの

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from flask import Flask
app = Flask(__name__)
from flask import Flask app = Flask(__name__)
from flask import Flask
app = Flask(__name__)

に相当する、という理解。

5〜7行目では、localhostをブラウザがリクエストした際に返信(res.render)するデータ。

app.listen(3000); はlistenメソッド。localhost:3000でアクセスできるサーバーを起動。

サーバーの起動:hello.ejsの作成 そしてejsファイルとは

次に
viewsディレクトリ(フォルダ)を作り、この中に”hello.ejs”の名前で下記ファイルを作る。
このhello.ejsファイルは、HTML内にJavaScriptを埋め込むような記述をするEJSファイル。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
% cat hello.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
<script src="/send_url.js"></script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>%
% cat hello.ejs <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Hello World</title> <script src="/send_url.js"></script> </head> <body> <h1>Hello World</h1> </body> </html>%
 % cat hello.ejs 
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Hello World</title>
    <script src="/send_url.js"></script>
  </head>
  <body>
    <h1>Hello World</h1>
  </body>
</html>%   

ファイル名”hello.ejs”の拡張子ejsは“Embedded JavaScript”の頭文字をとったもの。

このEJSは、HTMLとJavaScriptのコード両方を記述できるNode.jsのパッケージの1つ。詳細はEJSのページで。→EJS – Embedded JavaScript

因みに、この拡張子ejsのファイルを実行させる為には、ターミナル上でインストールする必要がある。
コマンドは"npm install -save ejs

ejsインストール後は、package.json内の”dependencies”にejsのバージョンが記載されている。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
cat package.json (抜粋)
"dependencies": {
"ejs": "^3.1.6",
"express": "^4.17.1"
}
cat package.json (抜粋) "dependencies": { "ejs": "^3.1.6", "express": "^4.17.1" }
cat package.json (抜粋)
  "dependencies": {
    "ejs": "^3.1.6",
    "express": "^4.17.1"
  }

サーバーの起動:app.jsの実行

app.jsのファイルにはexpressを使う準備と、listenメソッドでサーバーを起動するコマンドが記述されている。

このapp.jsを実行。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
node app.js
node app.js
node app.js

実行した時に問題があった場合、エラーメッセージが続きますが、問題無く起動できた場合には何も表示されない。
便りが無いのは無事の知らせ、と言う奴だろうか?違うかも知れないけれど今回はそのままとする。

app.listen(3000)とapp.js内に記述しているので、localhost:3000とブラウザに入れてHello Worldと画面出てきたらO.K.

以上が最初の一歩の備忘録。

amazonがブラックフライデー。
こちらのインベスターZも1巻から10巻までが今(2021/11/24現時点で後8日との表記)なら96円で買えます。
私も以前別のタイミングで買いましたが、参考になる考え方が多かった。
今は1巻から3巻まで読み放題で読むことも出来ますので、読んで気に入ったら買うと吉でしょう。

コメント

  1. […] Node.jsでWebアプリケーションを作る最初の一歩 […]

  2. […] Node.jsでWebアプリケーションを作る最初の一歩 […]

タイトルとURLをコピーしました