Node.js

作成日:2017-07-30
最終更新日:

サーバーサイド JavaScript

今まで JavaScript といえば、クライアント側での画面や情報を制御するための道具として考えられてきた。 しかし、サーバー側の言語としても使えることは知られていたし、また 2000 年初頭からの実例もあった。 とはいえ、サーバー側の言語として普及するのは 2010 年以降である。 きっかけになったのは Node.js だ。

JavaScript はサーバーサイド言語に適しているのか

JavaScript がサーバーサイド言語としても採用された理由に、どの OS でも仕様が共通だからというのがある。 というのも、クライアントサイドの JavaScript は広まっているので、 技術者にとっては新しい言語を覚える負担が少なくなるという利点がある。

と書いたが、これは誤りだという。本当の利点は、C10K 問題を解決することができるため、 ということだ。 C10K 問題とは、クライアントから Web サーバーへのリクエストが同時に1万件以上来た場合に、 従来型のサーバープログラムでは処理性能が急速に劣化することをいう。 C10K とは Client 10K 、いいかえれば 1万台のクライアント(1万件のクライアント側要求)のことをいう。 K は 1000 を表す単位である。

なぜ1万件なのかというと、クライアントを処理する方法との間に関連がある。 従来型ではプロセスやスレッドといった単位でクライアントを管理するのだが、 そのプロセスやスレッドの切り替えに多くの資源、すなわち時間やメモリーを要する。 一方、JavaScript にはプロセスやスレッドを管理する言語仕様をもたない。 ではどうするか。自前で多数のクライアントを処理する仕組みをサーバーサイド JavaScript で作ればよい。 それを実現したのが、Node.js だった、というわけだ。

なお、C10K 問題というのは日本語としてはなじみにくい。クレージーキャッツの「五万節」を知っている人なら、 「五万件問題」とか「五万台問題」のほうがしっくりくるのではないかな。

Node.js によるプログラミングの例

let http = require('http');
let port = 3104;
let r = ["ベールのカテゴリー定理",
"開写像定理",
"閉グラフ定理",
"一様有界性定理",
"ラックス・ミルグラムの定理"];
let n;
let server = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    n = Math.floor(Math.random() * r.length)  ;
    res.end(r[n] + 'について述べよ。\n');
});

server.listen(port);
console.log('Server running *:' + port);

このプログラムを実装したが、現在は稼働していない。


Node.js のインストール

Node.js を本格的に使ってみたいと思い、2020-10-10 に WSL2 上にインストールすることにした。 調べてみると、Node.js を素でインストールするよりも、バージョンマネージャーをインストールしてから、 そこで Node.js をインストールするのがよさそうだ。

nvm のインストール

Node.js のバージョンを管理するのが NVM である。これをインストールしようとして、
https://docs.microsoft.com/ja-jp/windows/nodejs/setup-on-wsl2
を見てみた。すると、 < GitHub プロジェクト ページで NVM の最新リリースを確認し> というところで困った。このリンクは、 https://github.com/nvm-sh/nvm というところにリンクされているのだが、英語で書かれているので最新リリース番号がわからない。 latest というキーワードでページ内検索すると、 右側の欄に v0.36.0 という文字があった。これだ。ダウンロードする。

$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.36.0/install.sh | bash
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload  Upload   Total   Spent    Left  Speed
100 13527  100 13527    0     0  30194      0 --:--:-- --:--:-- --:--:-- 30194
=> Downloading nvm from git to '/home/username/.nvm'
=> Cloning into '/home/username/.nvm'...
remote: Enumerating objects: 316, done.
remote: Counting objects: 100% (316/316), done.
remote: Compressing objects: 100% (268/268), done.
remote: Total 316 (delta 36), reused 134 (delta 23), pack-reused 0
Receiving objects: 100% (316/316), 169.68 KiB | 421.00 KiB/s, done.
Resolving deltas: 100% (36/36), done.
=> Compressing and cleaning up git repository

=> Appending nvm source string to /home/username/.bashrc
=> Appending bash_completion source string to /home/username/.bashrc
=> Close and reopen your terminal to start using nvm or run the following to use it now:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion
$ command -v nvm
$ source ~/.bashrc
$ command -v nvm
nvm
$ nvm -ls
            N/A
iojs -> N/A (default)
node -> stable (-> N/A) (default)
unstable -> N/A (default)
$ nvm install node --lts
Downloading and installing node v14.13.1...
Downloading https://nodejs.org/dist/v14.13.1/node-v14.13.1-linux-x64.tar.xz...
################################################################################################################# 100.0%
Computing checksum with sha256sum
Checksums matched!
mv: '/home/username/.nvm/.cache/bin/node-v14.13.1-linux-x64/files/include' から '/home/username/.nvm/versions/node/v14.13.1/
include' へ移動できません: 許可がありません
Binary download failed, trying source.
Detected that you have 2 CPU core(s)
Number of CPU core(s) less than or equal to 2, running in single-threaded mode
Additional options while compiling:  --lts
Clang v3.5+ detected! CC or CXX not specified, will use Clang as C/C++ compiler!
Downloading https://nodejs.org/dist/v14.13.1/node-v14.13.1.tar.xz...
################################################################################################################# 100.0%
Computing checksum with sha256sum
Checksums matched!
$>./configure --prefix=/home/username/.nvm/versions/node/v14.13.1 --lts<
Node.js configure: Found Python 3.8.3...
Usage: configure [options]

configure: error: no such option: --lts
nvm: install v14.13.1 failed!

なんじゃこりゃあ!。どうも --lts というオプションを解釈しなかったらしく、 そのせいで最新版の 14.13.1 をインストールしようとしたらしいが、 それがインストールできないと言われたらしい。v14.13.1 はインストールできるのか?

$ nvm ls-remote | tail
 v14.6.0
 v14.7.0
 v14.8.0
 v14.9.0
v14.10.0
v14.10.1
v14.11.0
v14.12.0
v14.13.0

これじゃインストールできないな。lts を使うというせこい考えはやめて(どうせ自分だけだ)、 最新版を使ってやる。それに node だけでなく一切合切をインストールしてやる!

$ nvm install v14.13.0
(ものすごい量のコンパイル中メッセージが8時間以上続く)
if [ ! -r node -o ! -L node ]; then \
  ln -fs out/Release/node node; fi
nvm: install v14.13.0 failed!

やっぱり lts だけにする。

$ nvm ls-remote --lts | tail
v12.16.1   (LTS: Erbium)
v12.16.2   (LTS: Erbium)
v12.16.3   (LTS: Erbium)
v12.17.0   (LTS: Erbium)
v12.18.0   (LTS: Erbium)
v12.18.1   (LTS: Erbium)
v12.18.2   (LTS: Erbium)
v12.18.3   (LTS: Erbium)
v12.18.4   (LTS: Erbium)
v12.19.0   (Latest LTS: Erbium)
$ nvm install v12.19.0 | tail
Downloading and installing node v12.19.0...
Downloading https://nodejs.org/dist/v12.19.0/node-v12.19.0-linux-x64.tar.xz...
################################################################################################################# 100.0%
Computing checksum with sha256sum
Checksums matched!
mv: '/home/username/.nvm/.cache/bin/node-v12.19.0-linux-x64/files/include' から '/home/satosi/.nvm/versions/node/v12.19.0/
include' へ移動できません: 許可がありません
Binary download failed, trying source.

ここで ctrl-c をクリックして中止した。しかし、

$ node --version
v12.19.0

なぜ、起動できているのだろう?(2020-10-10)

新たな NVM と Node.js のインストール

以前は Windows 10 の WSL2 にインストールした。こんどは Windows 11 のネイティブ環境に、 NVM をインストールすることにした。
https://learn.microsoft.com/ja-jp/windows/dev-environment/javascript/nodejs-on-windows
にしたがって、nvm-windows の 1.1.10 をインストールする。具体的には、
https://github.com/coreybutler/nvm-windows/releases
の 1.1.10 (インストール時の最新)の nvm-setup.exe をダウンロードし、実行する。ウィザードでインストールするフォルダを指定する。 デフォルトは
C:\Users\<username>\AppData\Roaming\nvm である。

> nvm

Running version 1.1.10.

Usage:

  nvm arch                     : Show if node is running in 32 or 64 bit mode.
  nvm current                  : Display active version.
  nvm install <version> [arch] : The version can be a specific version, "latest" for the latest current version, or "lts" for the
                                 most recent LTS version. Optionally specify whether to install the 32 or 64 bit version (defaults
                                 to system arch). Set [arch] to "all" to install 32 AND 64 bit versions.
                                 Add --insecure to the end of this command to bypass SSL validation of the remote download server.
  nvm list [available]         : List the node.js installations. Type "available" at the end to see what can be installed. Aliased as ls.
  nvm on                       : Enable node.js version management.
  nvm off                      : Disable node.js version management.
  nvm proxy [url]              : Set a proxy to use for downloads. Leave [url] blank to see the current proxy.
                                 Set [url] to "none" to remove the proxy.
  nvm node_mirror [url]        : Set the node mirror. Defaults to https://nodejs.org/dist/. Leave [url] blank to use default url.
  nvm npm_mirror [url]         : Set the npm mirror. Defaults to https://github.com/npm/cli/archive/. Leave [url] blank to default url.
  nvm uninstall <version>      : The version must be a specific version.
  nvm use [version] [arch]     : Switch to use the specified version. Optionally use "latest", "lts", or "newest".
                                 "newest" is the latest installed version. Optionally specify 32/64bit architecture.
                                 nvm use <arch> will continue using the selected version, but switch to 32/64 bit mode.
  nvm root [path]              : Set the directory where nvm should store different versions of node.js.
                                 If <path> is not set, the current root will be displayed.
  nvm [--]version              : Displays the current running version of nvm for Windows. Aliased as v.

私の環境では、このままでは node は起動しない。

> nvm list
No installations recognized.

nvm list available を実行すると、LTS で一番新しいのが 18.12.1 のようなのでこれをインストールする。 もっとも LTS のうちで一番新しいのをインストールするには nvm install --lts でいいと思ったのだが失敗してしまった。

> nvm install --lts
panic: runtime error: slice bounds out of range [:1] with length 0

goroutine 1 [running]:
main.versionNumberFrom({0x11c160b0, 0x5})
        C:/Users/corey/OneDrive/Documents/workspace/libraries/oss/coreybutler/nvm-windows/src/nvm.go:496 +0x116
main.getVersion({0x11c160b0, 0x5}, {0x5e9d26, 0x2}, {0x0, 0x0, 0x0})
        C:/Users/corey/OneDrive/Documents/workspace/libraries/oss/coreybutler/nvm-windows/src/nvm.go:233 +0x367
main.install({0x11c160b0, 0x5}, {0x5e9d26, 0x2})
        C:/Users/corey/OneDrive/Documents/workspace/libraries/oss/coreybutler/nvm-windows/src/nvm.go:273 +0xbb
main.main()
        C:/Users/corey/OneDrive/Documents/workspace/libraries/oss/coreybutler/nvm-windows/src/nvm.go:87 +0xaea

> nvm install 18.12.1
Downloading node.js version 18.12.1 (64-bit)...
Extracting node and npm...
Complete
npm v8.19.2 installed successfully.


Installation complete. If you want to use this version, type

nvm use 18.12.1

よし、大丈夫だ。設定しよう。

> nvm use 18.12.1
Now using node v18.12.1 (64-bit)

Node をインストールした理由は、プログラミング言語 Elm を使ってみたかったからだ。

その後、node.js を 18.16.0 にバージョンアップした。(2023-05-12)

まりんきょ学問所JavaScript 手習い > Node.js