Memo

メモ > 技術 > フレームワーク: Node.js

■Node.js
■概要 Node.js ... サーバーサイドで実行できるJavaScript npm ... Node Package Manager の略で、Node.jsのパッケージを管理するツール yarn ... npmの後に登場したパッケージ管理ツール npmの上位互換となっており、インストールの高速化など改良されたものになっている nvm ... システム内に複数バージョンのNode.jsをインストールし、切り替えて使うことができるようになる Node.js https://nodejs.org/ja/ Node.jsとはなにか?なぜみんな使っているのか? - Qiita https://qiita.com/non_cal/items/a8fee0b7ad96e67713eb いまさら聞けないNode.js | さくらのナレッジ https://knowledge.sakura.ad.jp/24148/ そもそもnpmからわからない https://zenn.dev/antez/articles/a9d9d12178b7b2 【Node.js】npmとyarnの違い - Qiita https://qiita.com/mzmz__02/items/4ba43b69c8878a9ca99e とほほのNode.js入門 - とほほのWWW入門 https://www.tohoho-web.com/ex/nodejs.html nvm で複数の Node.js バージョンを切り替えて使用する (Node Version Manager) - まくまくNode.jsノート https://maku77.github.io/nodejs/env/nvm ■導入 Node.js をインストール 手順中の「Tools for Native Modules」の画面では、「Automatically install the necessary tools.」にチェックを入れずに進める(デフォルトのまま)
>node -v v12.16.2 >node Welcome to Node.js v12.16.2. Type ".help" for more information. > console.log('Hello!'); Hello! undefined > .exit
■Webサーバを起動 C:\Users\refirio\Node\hello\app.js
const http = require('http'); var server = http.createServer( (request, response) => { response.end('Hello Node.js!'); } ); server.listen(3000);
以下で起動
>cd C:\Users\refirio\Node\hello >node app.js
ブラウザで以下にアクセスすると「Hello Node.js!」と表示される。Ctrl+C で終了できる http://localhost:3000/ ■npmのコマンド npm入門 - とほほのWWW入門 https://www.tohoho-web.com/ex/npm.html 「npm install パッケージ」とすることで、指定したパッケージをインストールできる インストールしたパッケージは package.json ファイルに書き込まれる package.json があれば、「npm install」とすることで再度パッケージをインストールできる ただし「npm install」を実行すると、「package-lock.json」の内容が書き換えられる可能性がある これを防ぐには「npm ci」を使うといい(原則こちらを使っておけば問題無さそう) `npm install` の代わりに `npm ci` が使えるかも(NPMおれおれAdvent Calendar 2019 - 04日目) | Ginpen.com https://ginpen.com/2019/12/04/npm-install-vs-ci/ 「また package-lock.json は(”lock” という名前に反して)node_modules の実際を反映するものだからです。本当にロックしちゃうとそれはそれで問題があったため変更されたようで。マジかよ。」 npmの依存関係とv7のロックファイルについて調べてみた https://zenn.dev/estra/articles/npm-lockfile-dependencies npm installの使い方とnpm ciの使い方 | 株式会社CONFRAGE ITソリューション事業部 https://confrage.jp/npm-install%E3%81%AE%E4%BD%BF%E3%81%84%E6%96%B9/ npm installとnpm ciの違いをメモする - CLOVER https://kazuhira-r.hatenablog.com/entry/2022/01/04/164924 npm install と npm ci の話 | PzGleaner https://pzgleaner.com/archives/npm-ci 「npm ci は node_modules ディレクトリを一度削除して、package.json との整合性をチェックした上で node_modules を再現します。」とあるように、 node_modulesディレクトリは再作成されるようだが、その場合でも処理は数秒で完了できた package-lock.jsonについて知りたくても聞けなかったこと - Qiita https://qiita.com/fj_yohei/items/7ca887a45e0855917279 npm install と npm ci って結局どう使うの?2023年版 - Mitsuyuki.Shiiba https://bufferings.hatenablog.com/entry/2023/03/15/215044 「npm ciのciは "Continuous Integration"ではなく、"Clean Install"」
■機能の検証
■HTMLを表示 C:\Users\refirio\Node\hello\app.js
const http = require('http'); var server = http.createServer( (request, response) => { response.setHeader('Content-Type', 'text/html'); response.write('<!DOCTYPE html>'); response.write('<html>'); response.write('<head>'); response.write('<meta charset="utf-8">'); response.write('<title>Node.js</title>'); response.write('</head>'); response.write('<body>'); response.write('<h1>Node.js</h1>'); response.write('<p>Node.js の世界へようこそ!</p>'); response.write('</body>'); response.write('</html>'); response.end(); } ); server.listen(3000); console.log('Server started.');
■HTMLファイルを読み込んで表示 C:\Users\refirio\Node\hello\index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Node.js</title> </head> <body> <h1>Node.js</h1> <p>Node.js の世界へようこそ!</p> </body> </html>
C:\Users\refirio\Node\hello\app.js
const http = require('http'); const fs = require('fs'); var server = http.createServer( (request, response) => { fs.readFile('./index.html', 'UTF-8', (error, data) => { response.writeHead(200, {'Content-Type': 'text/html'}); response.write(data); response.end(); }); } ); server.listen(3000); console.log('Server started.');
■テンプレートエンジンEJS(Embedded JavaScript Templates)を使う
>npm install -g ejs
実行時に「Error: Cannot find module 'ejs'」と表示される場合、以下も実行する
>npm init >npm install --save ejs
C:\Users\refirio\Node\hello\app.js
const http = require('http'); const fs = require('fs'); const ejs = require('ejs'); var server = http.createServer( (request, response) => { const data = fs.readFileSync('./index.ejs', 'UTF-8'); var content = ejs.render(data, { title: 'Node.js', content: 'これはEJSを使ったページです。', }); response.writeHead(200, {'Content-Type': 'text/html'}); response.write(content); response.end(); } ); server.listen(3000); console.log('Server started.');
C:\Users\refirio\Node\hello\index.ejs
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title><%=title %></title> </head> <body> <h1><%=title %></h1> <p><%=content %></p> </body> </html>
■複数のページを作る C:\Users\refirio\Node\hello\app.js
const http = require('http'); const fs = require('fs'); const ejs = require('ejs'); const url = require('url'); var server = http.createServer( (request, response) => { var parameters = url.parse(request.url); switch (parameters.pathname) { case '/': var data = fs.readFileSync('./index.ejs', 'UTF-8'); var content = ejs.render(data, { title: 'Node.js', content: 'これはEJSを使ったページです。', }); response.writeHead(200, {'Content-Type': 'text/html'}); response.write(content); response.end(); break; case '/other': var data = fs.readFileSync('./other.ejs', 'UTF-8'); var content = ejs.render(data, { title: 'サブページ', content: 'これはサブページです。', }); response.writeHead(200, {'Content-Type': 'text/html'}); response.write(content); response.end(); break; case '/style.css': var data = fs.readFileSync('./style.css', 'UTF-8'); response.writeHead(200, {'Content-Type': 'text/css'}); response.write(data); response.end(); break; } } ); server.listen(3000); console.log('Server started.');
C:\Users\refirio\Node\hello\index.ejs
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title><%=title %></title> <link rel="stylesheet" href="./style.css"> </head> <body> <h1><%=title %></h1> <p><%=content %></p> <ul> <li><a href="/other">/other</a></li> </ul> </body> </html>
C:\Users\refirio\Node\hello\other.ejs
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title><%=title %></title> <link rel="stylesheet" href="./style.css"> </head> <body> <h1><%=title %></h1> <p><%=content %></p> <a href="/">戻る</a> </body> </html>
C:\Users\refirio\Node\hello\style.css
h1 { color: #FF4500; }
■アプリケーション変数を使う ※すべての人が共通して参照できるデータ ※グローバル変数がそのような値となる C:\Users\refirio\Node\hello\app.js
const http = require('http'); const fs = require('fs'); const ejs = require('ejs'); const url = require('url'); var number = 0; var server = http.createServer( (request, response) => { var parameters = url.parse(request.url); switch (parameters.pathname) { case '/': var data = fs.readFileSync('./index.ejs', 'UTF-8'); number++; var content = ejs.render(data, { title: 'Node.js', content: 'これはEJSを使ったページです。', count: number, }); response.writeHead(200, {'Content-Type': 'text/html'}); response.write(content); response.end(); break; case '/style.css': var data = fs.readFileSync('./style.css', 'UTF-8'); response.writeHead(200, {'Content-Type': 'text/css'}); response.write(data); response.end(); break; } } ); server.listen(3000); console.log('Server started.');
C:\Users\refirio\Node\hello\index.ejs
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title><%=title %></title> <link rel="stylesheet" href="./style.css"> </head> <body> <h1><%=title %></h1> <p><%=content %></p> <p>count=<%=count %></p> </body> </html>
C:\Users\refirio\Node\hello\style.css
h1 { color: #FF4500; }
■Express
>mkdir express-app >cd express-app >npm init >npm install --save express
※「express」というフォルダ名にすると、expressインストール時に 「Refusing to install package with name "express" under a package npm ERR! also called "express".」 というエラーになる C:\Users\refirio\Node\express-app\index.js
var express = require('express'); var app = express(); app.get('/', (req, res) => { res.send('Welcome to Express!'); }); app.listen(3000, () => { console.log('Started server port: 3000'); });
>node index.js
ブラウザで以下にアクセスすると「Welcome to Express!」と表示される。Ctrl+C で終了できる http://localhost:3000/ ■EJSを使う
>npm install --save ejs
C:\Users\refirio\Node\express-app\index.js
var express = require('express'); var ejs = require('ejs'); var app = express(); app.engine('ejs', ejs.renderFile); app.use(express.static('public')); app.get('/', (req, res) => { res.render('index.ejs', { title: 'トップページ', content: 'これはExpressによるトップページです。' }); }); app.get('/other', (req, res) => { res.render('other.ejs', { title: 'サブページ', content: 'これはExpressによるサブページです。' }); }); app.listen(3000, () => { console.log('Started server port: 3000'); });
C:\Users\refirio\Node\express-app\views\index.ejs
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title><%=title %></title> <link rel="stylesheet" href="./style.css"> </head> <body> <h1><%=title %></h1> <p><%=content %></p> <ul> <li><a href="/other">/other</a></li> </ul> </body> </html>
C:\Users\refirio\Node\express-app\views\other.ejs
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title><%=title %></title> <link rel="stylesheet" href="./style.css"> </head> <body> <h1><%=title %></h1> <p><%=content %></p> <a href="/">戻る</a> </body> </html>
C:\Users\refirio\Node\express-app\public\style.css
h1 { color: #FF4500; }
■Express Generator を使う
>npm install -g express-generator >cd C:\Users\refirio\Node >express -e ex-gen-app >cd ex-gen-app >npm install >npm start
ブラウザで以下にアクセスすると「Welcome to Express!」と表示される。Ctrl+C で終了できる なお「npm start」の代わりに「node bin\www」としても起動できる http://localhost:3000/

Advertisement