Nodejs¶
はじめに¶
Node.jsは、JavaScript実行環境です。
サーバーサイドでもスタンドアロン環境でもマシン上でJavaScriptを実行する環境です。
環境の用意¶
MacOS¶
brewでインストールするのが簡単です。
brew info nodeの実行結果を表示隠す
% brew info node
==> node: stable 21.5.0 (bottled), HEAD
Platform built on V8 to build network applications
https://nodejs.org/
/opt/homebrew/Cellar/node/21.5.0 (2,233 files, 63.3MB) *
Poured from bottle using the formulae.brew.sh API on 2024-01-03 at 12:18:30
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/n/node.rb
License: MIT
==> Dependencies
Build: pkg-config ✔, python@3.12 ✔
Required: brotli ✔, c-ares ✔, icu4c ✔, libnghttp2 ✔, libuv ✔, openssl@3 ✔
==> Options
--HEAD
Install HEAD version
==> Analytics
install: 192,945 (30 days), 594,619 (90 days), 2,044,186 (365 days)
install-on-request: 168,584 (30 days), 511,796 (90 days), 1,792,092 (365 days)
build-error: 461 (30 days)
brewで Node.jsをインストールします。
% brew install node
:
はじめてのNode.js スクリプト実行¶
hello.js¶
console.log('Hello, Node.js world.');
実行するには、
% node hello.js
Hello, Node.js world.
ライブラリのインストール¶
Node.jsは、様々なライブラリをnpmで管理します。
npm install¶
mathjsライブラリをインポートします。
% npm install mathjs
added 11 packages in 2s
2 packages are looking for funding
run `npm fund` for details
% npm list
hello@ /Users/foobar/node.js/hello
└── mathjs@12.3.0
ライブラリを使用する¶
const math = require('mathjs')
console.log('Hello, NodeJS world. mathjs pi=', math.pi);