2019年11月16日
2020年11月2日
【Node.js】Webサーバーを起動して「Hello World」してみる

Node.jsをインストール、そして npm コマンドを使ってみるところまでやりました。
今回は、Node.jsを使ってサーバを立ち上げてブラウザに「Hello World」と表示させてみます。
初期化
まず、空のディレクトリを用意してその中に入ります。
$ mkdir express-app
$ cd express-app/
以下のコマンドを打ちます。
$ 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 json` 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.
続いていくつかプロジェクトの情報について入力します。
ここでは練習なので特に何も入力せずリターンキーを押しておきます。
package name: (express-app)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
入力し終えたら最後に作成される package.json の内容を確認します。
{
"name": "express-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)
最期にOKかどうか問われるので問題がなければリターンキーを押して終了です。
Webサーバーの本体となるJavaScriptファイルを作成する
package.json を基にしてJavaScriptのWebサーバーを作成します。
まず作成するのがWebサーバーのエントリポイント(最初に起動するプログラム)となる app.js です。
$ touch app.js
テキストエディタを使用して app.js を編集します。
以下の6行を入力します。
var http=require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'ContentType’: 'text/plain'});
res.end('HelloWorld');
});
server.listen(3000);
わずか6行のコードですが、これでWebサーバーとして機能します。
何だか不思議ですね!
ここでコマンドを打ってみます。
$ node app.js
サーバーが起動されて新しくコマンドを入力できない状態になりました。
これはNode.jsのプロセスが新しく起動して、HTTPリクエストを待ち受ける状態になっているのです。
Webブラウザで http://localhost:3000/ にアクセスしてみると、以下のように表示されました。

これでローカルで動作しているWebサーバーにアクセスできました!
次回は app.js に入れた6行のコードについて1つずつ見ていきたいと思います。

フォローお願いします