Node.js – Visual Studio Code の利用 on Ubuntu No.52

自己投資の一つとしてチャレンジしている Programming の独習状況を Blog で公開しています。今回は Ubuntu の環境で Node.js を Visual Studio Code 上で実行したいと思います。

————————————
▼1. Visual Studio Code を利用して Node.js のコードを書いてみる
————————————
Visual Studio Code は 色々な言語を Windows, Linux, Mac 上で実行できる環境を提供しています。今回は Node.js を試してみます。

Node.js は JavaScript を実行できる Open Source の環境です。Node.js のアプリを動かすには、Node.js の runtime のインストールが必要です。

Node.js の特徴として、シングルプロセスで動作し、他の JavaScript の Code によるブロッキングが発生しないよう非同期 I/O が可能です。そのため、単一サーバーにて何千もの同時実行接続を処理できます。Node.js は Chrome などブラウザに対して JavaScript を書くことができ、クライアントおよびサーバーサイドのコーディングが可能です。(参考情報) https://nodejs.dev/learn

————————————
▼2. 事前準備
————————————
2-1. Ubuntu 20.04.2 LTS の利用
Ref: https://releases.ubuntu.com/20.04/

2-2. Visual Studio Code のインストール
Ref: https://code.visualstudio.com/docs/setup/linux

sudo snap install --classic code

2-3. curl のインストール
必須ではありません。後ほど http サイトの疎通テストで利用します。

sudo apt install curl

2-4. Node.js のインストール
Node.js JavaScript runtime および npm をインストール

# Ubuntu
curl -fsSL https://deb.nodesource.com/setup_18.x |sudo -E bash -
sudo apt-get install -y nodejs

Ref1:NodeSource Node.js Binary Distributions
Ref2:Download | Node.js (nodejs.org)

————————————
▼3. Web サイトで Hello World を表示する
————————————
3-1. ディレクトリ作成後、application を VS Code で開きます。

mkdir my-app
cd my-app
code .

3-2. index.js を作成し、browser で Hellow World を表示します。
以下のような index.js を作成し、Terminal から node index.js を実行します。

const http=require('http')
const hostname='127.0.0.1'
const port=3000

const server = http.createServer((req,res)=> {
    res.statusCode=200
    res.setHeader('Content-Type','text/html')
    res.end('<h1>Hello World</h1>\n<h2>How are you?</h2>')
})

server.listen(port,hostname,() => {
    console.log(`Server running at http:://${hostname}:${port}/`)
})
index.js

3-3. Port 3000 の localhost のサイトをブラウザで開きます。

3-4. Curl コマンドでも http 通信の疎通確認してみます。
HTTP Status 200 が返ることを確認。

$ curl -s -v http://localhost:3000
*   Trying 127.0.0.1:3000...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET / HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.68.0
> Accept: */*
> 
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Content-Type: text/html
< Date: Sat, 04 Jun 2022 07:03:43 GMT
< Connection: keep-alive
< Keep-Alive: timeout=5
< Content-Length: 42
< 
<h1>Hello World</h1>
* Connection #0 to host localhost left intact

3-5. lsof コマンドを使って port 3000 を利用しているプロセスを確認してみます。
node のプロセスが port 3000 を利用していることが分かります。

$  lsof -i:3000
COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node    5762 ubuntu20   18u  IPv4  65730      0t0  TCP localhost:3000 (LISTEN)

————————————
▼4. 参考情報
————————————
(1) https://code.visualstudio.com/docs/nodejs/nodejs-tutorial
(2) https://nodejs.dev/learn
(3) Build an HTTP Server (nodejs.dev)

以上です。参考になりましたら幸いです。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です