はじめてのプログラミング
ファイル構成
start/
├── hello.js
├── load_file.js
└── memo.txt
node コマンド
Node.js では node コマンドで .js ファイルを実行できます。拡張子 .js は省略可能です。
node プログラムファイル
プログラム実行
コンソールログを出力するプログラムを hello.js を作成します。
hello.js
console.log("Hello Node!")
ターミナルで実行
node hello
結果
Hello Node!
hello.js
console.log("Hello Node!")
var message = 'This is Node.js'
console.log(message)
もう一度、node コマンドで実行します。
結果
Hello Node!
This is Node.js
ファイル読み込み
// 1. require() で fs モジュールを読み込み
const fs = require("fs");
// ファイルパス
const filePath = "data/memo.json";
// 2. fs.readFile() でファイルを非同期読み込み
fs.readFile(filePath, "utf-8", loadMemo);
// コールバック関数
function loadMemo(err, data) {
// 4. 読み込み完了後に実行される
// JSON文字列 → JavaScriptオブジェクトに変換
const memo = JSON.parse(data);
console.log("タイトル:", memo.title);
console.log("項目:", memo.items);
}
// 3. ファイル読み込み中のメッセージ
console.log("ファイル読み込み中...");
REPLの基本
REPLとは
REPL(リプル)はRead-Eval-Print Loopの略で、ユーザーとインタプリタが対話的にコードを実行して、入力、評価、出力の繰り返す作業を指します。インタプリタとは、コンピュータが実行できるようにコード変換しながら同時に実行していくソフトウェアです。
REPLの開始
Node.jsのRELPを利用するには、nodeコマンドで開始します。
ターミナル
node
結果
Welcome to Node.js v12.18.2.
プログラムの入力
ターミナルにプログラムを入力して実行します。
> 2+3
5
> 3*1.5
4.5
> x = 5
5
> y = 2
2
> x / y
2.5
REPLの終了
.exitで REPLを終了します。
> .exit
REPLの基本コマンド
REPLの主なコマンドは以下のとおりです。
| コマンド | 動作 |
|---|---|
| Ctrl + C | 現在のターミナル終了 |
| Ctrl + C(2回) | 終了 |
| Ctrl + D | 終了(ターミナルの終了と同じ) |
| Tab | コマンドを一覧表示 |
| .help | 入力コマンドのヘルプ表示 |
| .save | ファイル保存 |
| .load | ファイル読み込み |
node コマンド実行
JSファイル作成
「hello.js」ファイルを作成して、console.log() を実行します。
hello.js
console.log("Hello Node!");
実行
node コマンドで hello.js を実行してみましょう。
node hello.js
結果
Hello Node!
ファイル操作
ファイル読み込み
.load コマンドで外部ファイルを読み込みます。
.load ファイル名
.loadコマンドで、「hello.js」を実行してみます。
node
> .load hello.js
結果
console.log('Hello Node!');
Hello Node!
undefined
ファイル保存
プログラムを1行ずつ実行して .saveでファイル保存できます。
.save ファイル名
REPLでプログラムを入力して「hello.js」に保存してみます。
ターミナル
> var message = 'Hello Tokyo'
'Hello Tokyo'
> console.log(message)
Hello Tokyo
undefined
> .save hello.js
Session saved to: hello.js
> .exit
プログラム追記の確認
hello.js にプログラムが追記されているか確認してみましょう。
console.log("Hello Node!")
var message = 'Hello Tokyo'
console.log(message)
コース内レッスン
- 1
Lesson 1
Node.js とは
レッスンを見る - 2
Lesson 2
標準モジュール
レッスンを見る - 3
Lesson 3
Webサーバ
レッスンを見る - 4
Lesson 4
npm
レッスンを見る - 5
Lesson 5
Express 1
レッスンを見る - 6
Lesson 6
Express 2
レッスンを見る - 7
Lesson 7
MySQLの利用
レッスンを見る - 8
Lesson 8
MySQLの基本
レッスンを見る - 9
Lesson 9
Router と MVC
レッスンを見る - 10
Lesson 10
EJSの基本
レッスンを見る - 11
Lesson 11
EJSのASPタグ
レッスンを見る - 12
Lesson 12
EJSのレイアウト
レッスンを見る - 13
Lesson 13
コントローラー
レッスンを見る - 14
Lesson 14
モデル
レッスンを見る - 15
Lesson 15
セッション
レッスンを見る - 16
Lesson 16
ミドルウェア
レッスンを見る - 17
Lesson 17
POSTリクエスト
レッスンを見る - 18
Lesson 18
Socket.io
レッスンを見る - 19
Lesson 19
セッション
レッスンを見る - 20
Lesson 20
Node.js の脆弱性対応
レッスンを見る - 21
Lesson 21
簡易チャットアプリ
レッスンを見る - 23
Lesson 23
Webサーバのリクエスト
レッスンを見る - 26
Lesson 26
REPL
レッスンを見る - 27
Lesson 27
ビルド
レッスンを見る - 28
Lesson 28
CRUD
レッスンを見る